本文介绍了如何排序列表<枚举,集合>通过枚举的顺序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

枚举:

 public enum ComponentType {
    INSTRUCTION, ACTION, SERVICE, DOMAIN, INTEGRATION,  OTHER, CONTEXT;
 }

A类:

 public class A
 {
    String name;
    ComponentType c;
    public A(String name, ComponentType c)
    {
      this.name = name;
      this.c = c;
    }

 }   

代码:

 List<A> l = new ArrayList<A>();
 l.add(new A("ZY", ACTION));  
 l.add(new A("ZY0", INSTRUCTION));  
 l.add(new A("ZY1", DOMAIN));  
 l.add(new A("ZY2", SERVICE));  
 l.add(new A("ZY3", INSTRUCTION));  
 l.add(new A("ZY4", ACTION));  

如何根据枚举顺序排列列表?

How to sort list according to enum order?

推荐答案

您应该简单地委托已经提供的枚举compareTo()方法,并反映声明顺序(基于 ordinal value):

You should simply delegate to the enum compareTo() method which is already provided and reflects the declaration order (based on the ordinal value):

Collections.sort(list, new Comparator() {
    @Override
    public int compare(A a1, A a2) {
        return a1.getType().compareTo(a2.getType());
    }
});

或者,如果您认为组件类型为您的元素提供自然顺序,您可以使A类本身实现 Comparable ,并将 compareTo 方法委托给 ComponentType 一。

Or, if you think that the component type provides the "natural order" for your elements, you can make the A class itself implement Comparable and also delegate the compareTo method to the ComponentType one.

这篇关于如何排序列表&lt;枚举,集合&gt;通过枚举的顺序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 04:07