枚举中的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,说明两个值是相同的,如果小于零,则说明该值在之前

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容