- 论坛徽章:
- 0
|
There is a very good way to sort a ArrayList instead of manually checking every element in the ArrayList.
The basic idea is making the element Object implement Comparable interface,and then implement the method "CompareTo" with the logic we want, and Add user Collections class's sort method to sort.
Here is one of the example, we want to sort a list of Competitors first by their last name, if they have the same last name , then sort by first name
Competitor
public class Competitor implements Comparable{
private String lastName;
private String firstName;
public Competitor(String lastName, String firstName){
this.lastName = lastName;
this.firstName = firstName;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public int compareTo(Object o) {
if(o instanceof Competitor){
Competitor competitor = (Competitor)o;
int compareResult = this.getLastName().toUpperCase().compareTo(competitor.getLastName().toUpperCase());
if(compareResult != 0)
return compareResult;
compareResult = this.getFirstName().toUpperCase().compareTo(competitor.getFirstName().toUpperCase());
if(compareResult !=0)
return compareResult;
}else
return 0;
return -1;
}
}
And here is the testing code
public class TestCompare {
@SuppressWarnings({ "unchecked", "unchecked", "unchecked" })
public static void main(String[] args){
Competitor comp1 = new Competitor("Abc","bcd");
Competitor comp2 = new Competitor("Bcd","abc");
Competitor comp3 = new Competitor("bcd","bcd");
ArrayListCompetitor> dataList = new ArrayListCompetitor>();
dataList.add(comp2);
dataList.add(comp1);
dataList.add(comp3);
for(int i=0; idataList.size();i++){
Competitor comp = dataList.get(i);
System.out.println("Before:"+comp.getLastName()+"\t"+comp.getFirstName());
}
// if (comp1 instanceof Comparable){
Collections.sort(dataList);
System.out.println("\n");
/// }
for( int i=0; idataList.size(); i++){
Competitor comp = dataList.get(i);
System.out.println("After:"+comp.getLastName()+"\t"+comp.getFirstName());
}
}
}
and here is the result
Before:Bcd abc
Before:Abc bcd
Before:bcd bcd
After:Abc bcd
After:Bcd abc
After:bcd bcd
本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u/2956/showart_272709.html |
|