Dave's Brain

Browse - Programming Tips - How do I sort an ArrayList without modifying the class in the ArrayList?

Date: 2010aug7
Language: java
Keywords: Comparable

Q.  How do I 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); }

Add a comment

Sign in to add a comment
Copyright © 2008-2017, dave - Code samples on Dave's Brain is licensed under the Creative Commons Attribution 2.5 License. However other material, including English text has all rights reserved.