Home  >  Q&A  >  body text

How to sort objects of different classes in java

Suppose two classes A and B have a common attribute date. I want to sort the two List<A> and List<B> according to date. What is the best way to do it?

The method I know is to write a base class, then A and B inherit this base class, and then call Collections.sort() to sort.

Is there a better way, or using reflection to write a similar method? Or is there a ready-made library that can be used?

学习ing学习ing2707 days ago833

reply all(3)I'll reply

  • 天蓬老师

    天蓬老师2017-06-14 10:54:58

    Using the method you mentioned above is a better method. 1. You can use the API provided by Java itself to reduce the amount of code. 2. The above method is also quite good in terms of code style.
    Another idea is to extract the dates of each class A and B and associate them with the A and B objects themselves. For example, implement a class Index. There are two attributes in Index, date and references to class A and B objects, or id, each A and B class object is associated with an Index object, and then the Index objects are sorted, and then the object corresponding to A or B is found through the id, in the same order as the index object, that is, sorted.

    reply
    0
  • 欧阳克

    欧阳克2017-06-14 10:54:58

    list.sort((l1,l2) -> l1.getDate().compareTo(l2.getDate()));

    reply
    0
  • typecho

    typecho2017-06-14 10:54:58

    1. Make a Base Class, A and B extend it

    2. Make an Interface, A and B implements

    3. Make a List<Object> and then sort it. The type needs to be forced in the Comparator

    4. Get a Wrapper class, wrap A and B, then put them in List and sort them

    reply
    0
  • Cancelreply