当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。