How to sort objects of different classes in java
学习ing
学习ing 2017-06-14 10:52:58
0
3
795

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
学习ing

reply all(3)
Peter_Zhu

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.

学霸
list.sort((l1,l2) -> l1.getDate().compareTo(l2.getDate()));
typecho
  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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!