Possible Duplicate:
How to sort an arraylist of objects by a property?
public static void main(String args[]){
List<Emp> unsortList = new ArrayList<Emp>();
unsortList.add(new Emp(109));
unsortList.add(new Emp(106));
unsortList.add(new Emp(103));
unsortList.add(new Emp(108));
unsortList.add(new Emp(101));
}
public class Emp {
Integer eid;
public Emp(Integer eid) {
this.eid=eid;
}
}
Emp is user defined class & stored in ArrayList. How sort ArrayList.
asked Oct 28, 2012 at 9:51
-
3You probably should have tried Google before asking your question here, there are LOTS of info on this topic.Egor– Egor2012年10月28日 09:53:24 +00:00Commented Oct 28, 2012 at 9:53
2 Answers 2
Check out Collections#sort(List list, Comparator c)
It allows you supply your own Comparator
which you can use to define how the objects will be matched
answered Oct 28, 2012 at 9:54
Comments
Implement Comparable<Emp>
and use Collections.sort
to sort the list
public class Emp implements Comparable<Emp> {
Integer eid;
public Emp(Integer eid) {
this.eid = eid;
}
@Override
public int compareTo(Emp o) {
return eid.compareTo(o.eid);
}
}
answered Oct 28, 2012 at 9:53
Comments
lang-java