Sorting an ArrayList
Hi guys.
If I have an ArrayList containing a number of Objects of a class I have created and I want to sort this list based upon an attribute of the objects, is this possible?
If that isnt clear , I have a list containing lots of objects of the class Product, and one of the attributes of this is called size (ie jumper.getSize()), which is a numerical value. If I wanted to sort this list so that whichever has the lowest size is first scaling up to the highest sizes last, is this possible?
Many thanks.
[530 byte] By [
welshn3ila] at [2007-11-26 19:51:43]

[url= http://java.sun.com/javase/6/docs/api/java/util/Collections.html#sort(java.util.List)]sort(List)[/url] or [url= http://java.sun.com/javase/6/docs/api/java/util/Collections.html#sort(java.util.List,%20java.util.Comparator)]sort(List, Comparator)[/url]
Here's a demo:
import java.util.*;
class Thing {
String string;
int ing;
public Thing(String string, int ing) {
this.string = string;
this.ing = ing;
}
public String toString() {
return "(" + string + "," + ing + ")";
}
}
class StringComparator implements Comparator < Thing > {
public int compare(Thing thing1, Thing thing2) {
return thing1.string.compareTo(thing2.string);
}
}
class IngComparator implements Comparator < Thing > {
public int compare(Thing thing1, Thing thing2) {
if (thing1.ing < thing2.ing)
return -1;
else if (thing1.ing > thing2.ing)
return +1;
else
return 0;
}
}
public class SortDemo {
public static void main(String[] args) {
Thing[] things = {
new Thing("A", 10),
new Thing("B", 5),
new Thing("C", 7),
};
List < Thing > list = new ArrayList < Thing > ( Arrays.asList(things));
Collections.sort(list, new StringComparator());
System.out.println(list);
Collections.sort(list, new IngComparator());
System.out.println(list);
}
}
Note also that java.util.Arrays has similar sort methods for arrays, too.