public class seasons{
public enum compare{
summer(0), spring(1), winter(3), fall(4);
(assume the constructor is already coded)
}
}
我如何创建一种方法,将两个季节作为争论并比较季节的价值?
答案 0 :(得分:0)
与==运算符
比较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;
}
答案 1 :(得分:0)
查看代码中的评论
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
}
}