How to sort two different objects in a collection?

后端 未结 4 1956
夕颜
夕颜 2021-01-21 16:46

Suppose I have two classes CLassA and CLassB. And they have one atributte in common, for example the number of elements that each class holds.

How can i create a collect

4条回答
  •  离开以前
    2021-01-21 17:28

    Hmm.. is it possible for ClassA and ClassB to share an interface?

    interface InterfaceZ
    {
        int getCount();
    }
    
    class ClassA implements InterfaceZ
    {
        int getCount() { return _myArray.length; }
    }
    class ClassB implements InterfaceZ
    {
        int getCount() { return _complexCollection.size(); }
    }
    

    Then just sort the list like so:

    List myArray;
    
    ... fill up array ...
    
    Collections.sort(myArray, new Comparator() {
    public int compare(InterfaceZ o1, InterfaceZ o2) {
        return o2.getCount() - o1.getCount();
    }});
    

提交回复
热议问题