How to sort two different objects in a collection?

后端 未结 4 2107
夕颜
夕颜 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:23

    If you have access to the declaration of CLassA and ~B, then go with a common interface, if not you could write a Wrapper for both Classes:

    I defined - against the description - my own classes ~A and ~B, to have something to test. Imagine they're foreign source, and you just have access to the classes.

    import java.util.*;
    
    public class SortAB
    {
        class CLassA {
            int [] elements;
            public CLassA (int [] a) {elements = a;}
            public int getElementCount () {return elements.length;}
        }
    
        class CLassB {
            List  elements;
            public CLassB (List  l) {elements = l;}
            public int getElementCount () {return elements.size ();}
        }
    
        /** a common element-count-wrapper with compareTo method */     
        abstract class EcWrapper  implements Comparable  {
            public abstract int getElementCount ();
            public int compareTo (EcWrapper o) {return getElementCount () - o.getElementCount ();}
        }
        /** concrete Wrapper for CLassA */
        class EcAWrapper extends EcWrapper  {
            private CLassA inner;
            public EcAWrapper (CLassA t) {
                inner = t;
            }
            public int getElementCount () {return inner.getElementCount (); }
        }
        /** concrete Wrapper for CLassB */
        class EcBWrapper extends EcWrapper  {
            private CLassB inner;
            public EcBWrapper (CLassB t) {
                inner = t;
            }
            public int getElementCount () {return inner.getElementCount (); }
        }
    
        // testing
        public SortAB ()
        {
            int [] ia = {3, 5, 7, 6, 9, 11, 14}; 
            List  il = new ArrayList  (); 
            for (int i: ia) 
                il.add (i); 
            il.add (15);
            il.add (16);
    
            CLassA a = new CLassA (ia);
            CLassB b = new CLassB (il);
            List  list = new ArrayList  ();
            list.add (new EcBWrapper (b));
            list.add (new EcAWrapper (a));
            show (list);
            Collections.sort (list);
            show (list);
        }
    
        public static void main (String args[])
        {
            new SortAB ();
        }
    
        public static void show (List  list)
        {
            for (EcWrapper e: list) 
                System.out.println ("\t" + e.getElementCount ());
            System.out.println ("---");
        }
    }
    

提交回复
热议问题