0

just wanted to ask on how to compare index of enum of two objects:

          enum Face {ACE,TWO,THREE,FOUR,FIVE}
            static final Face[] FACES = Face.values();

            static final Random RAND = new Random();
            public static Red_Dog random() 
                {
                    return new Red_Dog(SUITS[RAND.nextInt(SUITS.length)], 
                                        FACES[RAND.nextInt(FACES.length)]);
                }
            public static void main(String[] args) 
                {
                Scanner input = new Scanner(System.in);
                Red_Dog c1 = Red_Dog.random();
                Red_Dog c2 = Red_Dog.random();
                while(c1.equals(c2))
                    {
                        c1 = Red_Dog.random();
                        c2 = Red_Dog.random();
                    }
                System.out.println("First card: "+c1 +  " Second card: " + c2);


                Result: First card: FIVE Second card: TWO

I want to compare first card(c1 - 1st object) and second card(c2 - 2nd object). What methods do I need to use?

JNEC
  • 1
  • 1
  • @ManoDestra enum values can be compared with either `equals` or `==` equivalently. The `equals` method is `final`, and uses identity comparison. – Andy Turner Apr 11 '16 at 20:51
  • Yes, I am aware of that. This question still touches on the same question though. – ManoDestra Apr 11 '16 at 21:07
  • @ManoDestra not really. Equality tells you that the cards are equal or not; the question is asking about which card is higher. – Andy Turner Apr 11 '16 at 21:08
  • @AndyTurner My error here. I've linked to the wrong duplicate. I'll correct that. – ManoDestra Apr 11 '16 at 21:11
  • Actually a dupe of this one: http://stackoverflow.com/questions/21626439/how-to-implement-the-java-comparable-interface, but it won't let me change the flag. – ManoDestra Apr 11 '16 at 21:13

1 Answers1

0

You can use ordinal() method to get index of an Enum. So by checking c1.ordinal() == c2.ordinla() you can check if their indexes are equal. But if you want to check for equality of Enum's you can just check with ==, no need for checking of indexes.

Here's an info about ordinal

  • I would strongly recommend that you read *Effective Java 2nd Ed Item 31*: "Use instance fields instead of ordinals", as well as paying heed to the statement in the linked Javadoc for [`Enum.ordinal()`](https://docs.oracle.com/javase/7/docs/api/java/lang/Enum.html#ordinal()): "Most programmers will have no use for this method. It is designed for use by sophisticated enum-based data structures, such as EnumSet and EnumMap.". – Andy Turner Apr 11 '16 at 20:49