2017-04-01 170 views
0
public class seasons{  

     public enum compare{ 

       summer(0), spring(1), winter(3), fall(4); 

       (assume the constructor is already coded) 
     } 
} 

我該如何創建一個方法,將兩個季節作爲參數進行比較並比較季節值?在java中比較枚舉類型

+3

[對比的Java枚舉成員?:==還是equals()]的可能的複製(HTTP://計算器。 com/questions/1750435/comparison-java-enum-members-or-equals) –

+1

你是指比較平等,還是在枚舉中的相對位置? –

+0

請遵守Java命名約定。 –

回答

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; 
    } 
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 
    } 
} 
+0

使用靜態方法Integer.compare(s1.order,s2.order)會更好,因爲它不必創建新的Integer對象並將第二個操作數值框裝到另一個Integer對象中。 – DarkRift

+0

謝謝@DarkRift,我添加了這個選項 – c0der