當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Java Enum compareTo()用法及代碼示例


Enum 類的 compareTo() 方法將此枚舉對象與定義的對象進行比較以進行排序。

枚舉常量隻能與相同類型的其他枚舉常量進行比較。

用法

public final int compareTo(E o)

參數

o- 比較的是枚舉對象

返回值

compareTo() 方法返回:

  1. 負整數,如果此枚舉小於定義的對象。
  2. 零,如果此枚舉等於定義的對象。
  3. 正整數,如果此枚舉大於定義的對象。

例子1

public class Enum_compareToMethodExample1 {

enum Grade{
A1,A2;
    }
public static void main(String[] args) {

        Grade first, second, third;

first = Grade.A1;

second = Grade.A2;

int val = first.compareTo(second);

if(val>0){

System.out.println("A1 is greater than A2.");
        }

else if(val<0){
System.out.println("A2 is greater than A1.");
        }

else{

System.out.println("A1 and A2 both are equal .");

        }
    }
}

輸出:

A2 is greater than A1.

例子2

public class Enum_compareToMethodExample2 {
//we can declare an enum inside a class or outside a class but not inside an method.
enum Season {
summer, winter, spring;
    }
public static void main(String[] args) {
    Season sesn1, sesn2, sesn3;
        sesn1 = Season.spring;
        sesn2 = Season.summer;
        sesn3 = Season.winter;
int val1 = sesn1.compareTo(sesn2);
int val2 =sesn1.compareTo(sesn3);
int val3 =sesn3.compareTo(sesn2);
System.out.println("Val1= "+val1+"   Val2= "+val2+"   Val3= "+val3);
if(val1>0&&val2;>0){
System.out.println("Spring is my Fav season amongst all seasons.");
        }
else if(val1<0&&val3;<0){
System.out.println("Summer is my fav season amongst all seasons.");
        }
else{
System.out.println("Winter is my favfav season amongst all seasons.");
        }
      }
    }

輸出:

Val1= 2   Val2= 1   Val3= 1
Spring is my Fav season amongst all seasons.

例子3

public class Enum_compareToMethodExample3{
enumColour{
red,Red;
    }

public static void main(String[] args) {
        Colour red, Red;
        red = Colour.red;
        Red = Colour.Red;
//Upper case has higher value than lower case.
int val = red.compareTo(Red);

if( val>0){
System.out.println("red is greater than Red.");
        }
else if(val<0){
System.out.println("Red is greater than red.");
        }
else{
System.out.println("red and Red both are equal .");
        }
    }
    }

輸出:

Red is greater than red.



相關用法


注:本文由純淨天空篩選整理自 Java Enum compareTo() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。