public class seasons{
public enum compare{
summer(0), spring(1), winter(3), fall(4);
(assume the constructor is already coded)
}
}
我将如何创建一个以 2 个季节为参数并比较季节值的方法?
与 == 运算符比较
public static void main(String[] args)
{
compareSeasons(Seasons.Summer, Seasons.Summer); //returns true;
compareSeasons(Seasons.Summer, Seasons.Autumn); //returns false
}
private enum Seasons{ Summer, Autumn, Winter, Spring; }
private static boolean compareSeasons(Seasons seasonOne, Seasons seasonTwo){
return seasonOne == seasonTwo;
}
查看代码中的注释
public enum Seasons{
summer(0), spring(1), winter(3), fall(4);
int order;
Seasons(int order){
this.order = order;
}
//a method that fits the signature of Comparator<T>
//https://docs.oracle.com/javase/7/docs/api/java/util/Comparator.html
public static int compare(Seasons s1, Seasons s2) {
//Box int to an Integer object, and delegate comparison to its
//comareTo
return new Integer(s1.order).compareTo(s2.order);
//or as DarkRift 3 proposed
//return Integer.compare(s1.order, s2.order);
}
public static void main(String[] args) {
//if you just want to check for equality you can do it simply by
//using the == operator
System.out.println(summer == summer); //returns true;
System.out.println(summer == winter); //returns false
//if you want to compare based on the int property, use a comperator
System.out.println(compare(summer, summer));//return 0 meaning equal
System.out.println(compare(summer, winter));//return -1 meaning smaller
System.out.println(compare(winter,summer));//return 1 meaning bigger
}
}