Sort a list of objects of another type

I have a list of objects that contain different types of objects, but one property is common to all. the list contains objects of the Field class, Button class, page class, etc., but one property is common among all, for example, "sequence_no" & I want to sort this list based on "sequence_no".

+4
source share
4 answers

I would suggest creating an interface, for example " Sequenceable" using a method getSequenceNo().

public interface Sequenceable {
    int getSequenceNo();
}

In the classes Field, Button, Pagemust implement this interface, and the method getSequenceNo()returns yours sequence_no.

Comparator .

, :

class MyComparator implements Comparator<Sequenceable> {

    @Override
    public int compare(Sequenceable o1, Sequenceable o2) {
        return o2.getSequenceNo() - o1.getSequenceNo();
    }
}

:

Collections.sort(list, new MyComparator());
+7

, (, , ...), , Comparator<Object>, java.lang.Object.getClass() casting switch.

- :

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;
        }

:

Collections.sort(list, new MyComparator());
0

- , .

0

.

Another way could be (which I don’t prefer performance, readability and cleanliness), create your own comparator that uses reflection, which checks enter, and then compare the property

0
source

Source: https://habr.com/ru/post/1607970/


All Articles