枚舉中的compareTo方法

image.png

package All.D13.Enum_;

public enum Constants {
Constants_A, Constants_B, Constants_C,Constants_D,Constants_E,
}

package All.D13.Enum_;

import java.util.concurrent.Callable;

public class Demon02 {
public static void main(String[] args) {
Constants tmp= Constants.valueOf("Constants_B");
Constants c[]=Constants.values();

    for (int i = 0; i < c.length; i++) {
        String message="";
        int result=tmp.compareTo(c[i]);
        if (result>0){
            message=tmp+"在"+c[i]+"的后"+result+"個位置";
        }else if (result<0){
            message=tmp+"在"+c[i]+"的前"+(-result)+"個位置";
        }else if (result==0){
            message=tmp+"與"+c[i]+"是同一個值";
        }
        System.out.println(message);
    }

}

}

Constants_B在Constants_A的后1個位置
Constants_B與Constants_B是同一個值
Constants_B在Constants_C的前1個位置
Constants_B在Constants_D的前2個位置
Constants_B在Constants_E的前3個位置

該方法主要用于比較兩個枚舉類型對象定義時候的順序!

如果是大于0,則說明該值在之后,如果等于0,說明兩個值是相同的,如果小于零,則說明該值在之前

?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容