Blog home: http://blog.csdn.net/minna_d
Imagine a scenario where A has n fields and a comparison function specifically for a. Each comparison function is reused in n multiple lines of business.
So, the question comes, and suddenly one day a adds a field in, and in the original scenario, the field should have a higher priority than all the other fields. There is no effect in other scenarios.
How to solve this problem?
1. Rewrite all of the original comparator classes, overriding their compare methods. This approach costs too much because N-Multiple places require If...else
2. A new method of comparator is only added to a particular scene before it is combined.
If there is a Collections.sort (Alist, Lists.newarrarylist (C1, C2, C3)) Such a data structure, then the problem is solved (in fact, it is very simple to write one).
But did not find, inadvertently in Apache.commons.collections found a can completely replace his class. Comparatorchain, the interior also saves all the sequencer with a linked list
C1 and C2 can be used as a sort of sequencer in the past.
Static class A {Integer n1; Integer N2; A (integer n1, integer n2) {this.n1 = n1; This.n2 = n2; } @Override Public String toString () {return "a{" + "n1=" + n1 + ", n2=" + n2 + '} '; }} public static void Main (string[] args) {list<integer> data = lists.newarraylist (3, 1, 3, 1, 3, 2, 4, 2, 2, 2, 2, 4, 4, 2, 3, 1, 3, 4, 1, 2); List<a> alist = Lists.newarraylist (); for (Integer i = 0; i < data.size (); i + = 2) {Alist.add (New A (Data.get (i), data.get (i + 1))); } comparatorchain Multisort = new Comparatorchain (); Multisort.addcomparator (New comparator<a> () {@Override public int compare (a O1, a O2) { Return Integer.compare (O1.N1, o2.n1); } @Override public boolean equals (Object obj) {return false; } }); Multisort.addcOmparator (New comparator<a> () {@Override public int compare (a O1, a O2) {Retu RN Integer.compare (O1.N2, o2.n2); } @Override public boolean equals (Object obj) {return false; } }); System.out.println ("Before sorting:" + Joiner.on (","). Join (alist)); Collections.sort (Alist, Multisort); System.out.println ("After sorting:" + Joiner.on (","). Join (alist)); }
Reuse of Java comparators