Search code examples
enumsjava-6

Comparing ENUMs in Java 6


I am trying to find best way to compare Enums in Java 6.

Say, I have an ENUM of Ticket Types which can be associated with a Traveler. If there is a list of travelers, I would like to know the traveler with the highest class of travel.

I can iterate thru the list of travelers, create a Set of unique TicketTypes, Convert to List, Sort them, Return the last element as the highest. I would like to know if there is a better way to do this?

 public enum TicketType {
    ECONOMY_NON_REF(1,"Economy Class, Non-Refundable"),
    ECONOMY_REF(2,"Economy Full Fare Refundable"),
    BUSINESS(3,"Business Class"),
    FIRST_CLASS(4,"First Class, Top of the world");

    private String code;
    private String description;
}

public class Traveler {
    private TicketType ticketType;
            public Traveler(TicketType ticketType) {
                this.ticketType = ticketType;
            }
}

@Test
public testCompareEnums{
    List<Traveler> travelersGroup1 = new ArrayList<Travelers>();
    travelersGroup1.add(new Traveler(TicketType.ECONOMY_REF));
    travelersGroup1.add(new Traveler(TicketType.BUSINESS));
    travelersGroup1.add(new Traveler(TicketType.ECONOMY_REF));
    travelersGroup1.add(new Traveler(TicketType.ECONOMY_NON_REF));

    //What is the best way to find the highest class passenger in travelersGroup1.
    assertEquals(TicketType.BUSINESS, getHighestClassTravler(travelersGroup1));

    List<Traveler> travelersGroup2 = new ArrayList<Travelers>();
    travelersGroup2.add(new Traveler(TicketType.ECONOMY_REF));
    travelersGroup2.add(new Traveler(TicketType.ECONOMY_NON_REF));
    travelersGroup2.add(new Traveler(TicketType.ECONOMY_REF));
    travelersGroup2.add(new Traveler(TicketType.ECONOMY_NON_REF));
    assertEquals(TicketType.ECONOMY_REF, getHighestClassTravler(travelersGroup2));
}

    private CredentialType getHighestClassTraveler(List travelers){
            Set uniqueTicketTypeSet = new HashSet();
            for (Traveler t: travelers) {
                     uniqueTicketTypeSet.add(t.getTicketType());
               }
             List<TicketType> uniqueTicketTypes = new ArrayList<TicketType>(uniqueTicketTypeSet);   
             Collections.sort(uniqueTicketTypes);
             return uniqueTicketTypes.get(uniqueTicketTypes.size()-1);
     }

Solution

  • There's a lot of problems with the code that you posted (it won't compile without fixing a lot of errors), but the easiest way is to make Traveler implement the Comparable interface, like so:

      public int compareTo(Traveler other) {
           return this.getTicketType().compareTo(other.getTicketType());
      }
    

    Then to find the the Traveler with the highest TicketType, you can simply do:

     Collections.max(travelers);