packagewjtest_01;
importjava.util.ArrayList;
importjava.util.Collections;
importjava.util.Comparator;
importjava.util.List;
publicclassListSort{
@SuppressWarnings("unchecked")
publicstaticvoidmain(String[] args){
List list =newArrayList();
// 创建3个学生对象,年龄分别是20、19、21,并将他们依次放入List中
Student s1 =newStudent();
s1.setAge(20);
s1.setUsable(true);
Student s2 =newStudent();
s2.setAge(19);
s2.setUsable(true);
Student s3 =newStudent();
s3.setAge(21);
s3.setUsable(false);
list.add(s1);
list.add(s2);
list.add(s3);
System.out.println("排序前:"+ list);
Collections.sort(list,newComparator() {
@Override
publicintcompare(Student o1, Student o2){
// 按照学生的年龄进行升序排列
if(o1.getAge() > o2.getAge()) {
return1;
}
if(o1.getAge() == o2.getAge()) {
return0;
}
return-1;
}
});
System.out.println("升序排序后:"+ list);
Collections.sort(list,newComparator() {
publicintcompare(Student o1, Student o2){
// 按照学生的年龄进行降序排列
if(o1.getAge() > o2.getAge()) {
return-1;
}
if(o1.getAge() == o2.getAge()) {
return0;
}
return1;
}
});
System.out.println("降序排序后:"+ list);
Boolean b1 =true;// 创建Boolean对象1
Boolean b2 =false;// 创建Boolean对象0
Boolean b3 =true;// 创建Boolean对象1
System.out.println(b1);
inti;
i = b1.compareTo(b2);// b1和b2进行比较
System.out.println(i);//1-0
i = b2.compareTo(b1);// b2和b1进行比较
System.out.println(i);//0-1
i = b1.compareTo(b3);// b1和b3进行比较
System.out.println(i);//1-1
}
}
classStudent{
privateintage;
privateBoolean isUsable;
publicintgetAge(){
returnage;
}
publicBooleanisUsable(){
returnisUsable;
}
publicvoidsetUsable(Boolean isUsable){
this.isUsable = isUsable;
}
publicvoidsetAge(intage){
this.age = age;
}
@Override
publicStringtoString(){
returngetAge()+"";
}
}