一个朋友问的排序问题,Collections.sort
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class MySort implements Comparable<MySort>{
private String name ;
private int age;
public MySort() {
super();
}
public MySort(String name, int age) {
super();
this.name = name;
this.age = age;
}
@Override
public String toString( ) {
return this.name+","+this.age;
}
public static void main(String rgs[]) {
List<MySort> list=new ArrayList<MySort>();
Collections.addAll(list,new MySort("zhangsan",22),
new MySort("wisi",22),
new MySort("lisi",25));
System.out.println("排序前:");
for(MySort so:list){
System.out.print(so.toString()+"..");
}
Collections.sort(list);
System.out.println("排序后:");
for(MySort so:list){
System.out.print(so.toString()+"..");
}
}
public int compareTo(MySort o) {
if(this.name.compareTo(o.name)==0){
return this.age-o.age;
}else{
return this.name.compareTo(o.name);
}
}
}
欢迎关注公众号:Java后端技术全栈