Programming Tips - Java: Sort an ArrayList without modifying the class in the ArrayList

Date: 2010aug7 Language: java Keywords: Comparable Q. Java: Sort an ArrayList without modifying the class in the ArrayList A. Use the custom compare option for Collections.sort() like this
import java.util.Collections; import java.util.Comparator; import java.util.ArrayList; class CustomCompare implements Comparator<MyEntry> { @Override int compare(MyEntry a, MyEntry b) { return a.field1.compareTo(b.field1); } } void exampleUse() { ArrayList<MyEntry> a = new ArrayList<<MyEntry>(); // Add things to array a Collections.sort(a, new CustomCompare); }