2015-10-19 58 views
1

我想创建一个具有多种类型对象的列表。所以,我已经建立了这个代码:如何订购具有多种类型对象的ArrayList

List<Entrate>lista = modelManager.getEntrataManager().getEntrate(); 
List<NotaSpese>listaSpese=modelManager.getNotaSpesaManager().getNotaSpese(); 

List<Object> listaMovimenti = new ArrayList<Object>(); 
listaMovimenti.addAll(lista); 
listaMovimenti.addAll(listaSpese); 

现在我想通过Entrate和NotaSpese领域数据订购此集合。

如何订购清单?

+2

实现[Comparator](https://docs.oracle.com/javase/8/docs/api/java/util/Comparator.html),并调用[Collections.sort](https:// docs。 oracle.com/javase/8/docs/api/java/util/Collections.html#sort-java.util.List-java.util.Comparator-)。 – GriffeyDog

+0

所以,我应该实现Entrata和NotaSpese类的比较器? – bircastri

+0

是的。但你最好弄清楚你的对象模型。它不建议有列表 user1697575

回答

5

使用自定义comparator

final class CustomComparator implements Comparator<Object> { 
    @Override 
    public int compare(Object o1, Object o2) { 
     // implement some logic for comparing and return an int value here 
    } 
} 

然后你就可以简单的使用方法Collections.sort

List<Object> listaMovimenti = ... 
Collections.sort(listaMovimenti, new CustomComparator()); 
0

嗯,首先它与混合型不可取的,有收藏。

但在你的情况下,你应该为集合中的每种类型实现Comparable接口。或者,你可以创建一个Comparator,在排序过程中调用它来比较你的不同类型。

然后你就可以用Collections.sort

0

排序我个人有两个EntrateNotaSpese是相互媲美,如果是一般的用法:

class Entrate implements Comparable<Entrate>, Comparable<NotaSpece> { 
    //Implementation with the comparers 
} 

class NotaSpese implements Comparable<Entrate>, Comparable<NotaSpece> { 
    //Implementation with the comparers 
} 

调用Collections.sort(listaMovimenti)然后将使用appropirate comparers。

希望我没有错过任何东西。