sort a list of different type of objects

后端 未结 4 1021
小鲜肉
小鲜肉 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 and use the java.lang.Object.getClass() and casting in an switch clasusule.

    Something like:

    public class MyComparator implements Comparator{
            @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());
    

    提交回复
    热议问题