list的排序算法改写
public class Main2 {
public static void main(String[] args) {
List<student> l = new ArrayList<student>();
student stu1 = new student("001","aaa",18);
student stu2 = new student("002","bbb",19);
student stu3 = new student("003","ccc",22);
student stu4 = new student("004","ddd",14);
student stu5 = new student("005","eee",17);
l.add(stu1);
l.add(stu4);
l.add(stu3);
l.add(stu5);
l.add(stu2);
Iterator<student> it = l.iterator();
while(it.hasNext()){
System.out.println(it.next());
}
//排序
System.out.println("-----------qian----------");
Collections.sort(l, new Comparator<student>() {
@Override
public int compare(student o1, student o2) {
if(o1.ID.compareTo(o2.ID)==0){
return o2.age-o1.age;
}
return o2.ID.compareTo(o1.ID);//从大到小 o1在前是从小到大
}
});
Iterator<student> it1 = l.iterator();
while(it1.hasNext()){
System.out.println(it1.next());
}
System.out.println("-----------hou----------");
}
}
set的排序算法改写
public class Main {
public static void main(String[] args) {
Set<student> setlist = new HashSet<student>();
student stu1 = new student("001","abc",18);
student stu2 = new student("002","def",18);
student stu3 = new student("003","hhh",18);
student stu4 = new student("001","abc",18);
setlist.add(stu1);
setlist.add(stu2);
setlist.add(stu3);
setlist.add(stu4);
System.out.println(stu1.equals(stu4));//判断stu1与stu2是否一样
Iterator<student> it = setlist.iterator();
while(it.hasNext()){
System.out.println(it.next());
}
List<student> list = new ArrayList<student>(setlist);
System.out.println("-----------qian----------");
Collections.sort(list, new Comparator<student>() {
@Override
public int compare(student o1, student o2) {
if(o1.ID.compareTo(o2.ID)==0){
return o2.age-o1.age;
}
return o2.ID.compareTo(o1.ID);//从大到小 o1在前是从小到大
}
});
Iterator<student> it1 = list.iterator();
while(it1.hasNext()){
System.out.println(it1.next());
}
System.out.println("-----------hou----------");
}
}