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?
天蓬老师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.
typecho2017-06-14 10:54:58
Make a Base Class, A and B extend it
Make an Interface, A and B implements
Make a List<Object> and then sort it. The type needs to be forced in the Comparator
Get a Wrapper class, wrap A and B, then put them in List and sort them