0
 public class seasons{     

        public enum compare{ 

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

               (assume the constructor is already coded)
       }
}

How would I create a method that takes in 2 seasons as arguements and compares the values of the seasons?

c0der
  • 18,467
  • 6
  • 33
  • 65

2 Answers2

0

Compare with == operator

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;
    }
Sim
  • 570
  • 1
  • 10
  • 22
0

See comments in code

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
    }
}
c0der
  • 18,467
  • 6
  • 33
  • 65
  • Using the static method Integer.compare(s1.order, s2.order) would be better as it won't have to create a new Integer object and box the second operand value to another Integer object. – DarkRift Apr 03 '17 at 00:37
  • Thank you @DarkRift , I added this option – c0der Apr 03 '17 at 04:27