sort a list of different type of objects

后端 未结 4 986
小鲜肉
小鲜肉 2021-01-14 01:57

I have a list of objects which contains different types of objects but a single property is common among all. list contains objects of Field class, Button Class, Page class

相关标签:
4条回答
  • 2021-01-14 02:12

    If there are a few classes you want to sort (Field,Button,Page...) you could do a Class that inherits from Comparator<Object> and use the java.lang.Object.getClass() and casting in an switch clasusule.

    Something like:

    public class MyComparator implements Comparator<Object>{
            @Override
            public int compare(Object o1, Object o2) {
                int o1prop,o2prop;
                switch (o1.getClass().toString()) {
                case "java.Button":
                    ((Button)o1prop).getSequence_no();
                    break;
    
                default:
                    break;
                }
    
                switch (o2.getClass().toString()) {
                case "java.Field":
                    ((Field)o1prop).getSequence_no();
                    break;
    
                default:
                    break;
                }
    
                return o1prop-o2prop;
            }
    

    And after that use:

    Collections.sort(list, new MyComparator());
    
    0 讨论(0)
  • 2021-01-14 02:13

    I'd suggest creating an interface, something like "Sequenceable" with a method getSequenceNo().

    public interface Sequenceable {
        int getSequenceNo();
    }
    

    Your Field, Button, Page classes should implement this interface and the getSequenceNo() method will return your sequence_no.

    Then you can implement your own Comparator and sort using this comparator.

    For example, your comparator will look like:

    class MyComparator implements Comparator<Sequenceable> {
    
        @Override
        public int compare(Sequenceable o1, Sequenceable o2) {
            return o2.getSequenceNo() - o1.getSequenceNo();
        }
    }
    

    Then you can sort with:

    Collections.sort(list, new MyComparator());
    
    0 讨论(0)
  • 2021-01-14 02:13

    The best and clean way is to have your class implementing an interface or extending a common base class .

    Other way can be (which i don't prefer becpz of performance, readability and cleanliness), create a custom comparator that uses reflection which checks the type and then compare the property

    0 讨论(0)
  • 2021-01-14 02:37

    All your objects should be exetended or inheritance by some and same super class, then the compiler will not ask you to explicitly change those objects.

    0 讨论(0)
提交回复
热议问题