0

我正在尝试找到比较 Java 6 中枚举的最佳方法。

比如说,我有一个 ENUM 票类型,可以与旅行者相关联。如果有旅行者名单,我想知道旅行等级最高的旅行者。

我可以遍历旅行者列表,创建一组独特的 TicketTypes,转换为列表,对它们进行排序,将最后一个元素返回为最高元素。我想知道是否有更好的方法来做到这一点?

 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);
     }
4

1 回答 1

1

您发布的代码存在很多问题(如果不修复很多错误,它将无法编译),但最简单的方法是让 Traveler 实现 Comparable 接口,如下所示:

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

然后要找到具有最高 TicketType 的 Traveler,您可以简单地执行以下操作:

 Collections.max(travelers);
于 2012-10-27T05:09:57.177 回答