Comparable 接口的使用
//学生类
package test;
public class Student implements Comparable<Student>{
private int age;
private String name;
public Student(int age,String name) {
this.age = age;
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public int compareTo(Student o) {
if(this.age>o.age) {
return 1;
} else if(this.age == o.age) {
return this.name.compareTo(o.name);
} else {
return -1;
}
}
@Override
public String toString() {
return this.name+" "+this.age;
}
}
//对象比较 测试文件
package test;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Vector;
public class Test4 {
public static void main(String[] args) {
/*Vector<String> v = new Vector<String>();
v.add("1");
v.add("4");
v.add("64");
v.add("2");
v.add("35");
v.add("4");
v.add("7");
Collections.sort(v);*/
//System.out.println(v);
List<Integer> list = new ArrayList<Integer>();
list.add(44);
list.add(33);
list.add(777);
list.add(77);
list.add(99);
list.add(26);
list.add(33);
Collections.sort(list);
System.out.println(list);
int i = Collections.binarySearch(list, 777);
System.out.println(i);
int b = Collections.max(list);
System.out.println(b);
int c = Collections.min(list);
System.out.println(c);
/*Collections.sort(list);
System.out.println(list);
Collections.reverse(list);
System.out.println(list);
Collections.replaceAll(list, 33, 66);
System.out.println(list);
int i = Collections.binarySearch(list, 77);
System.out.println(i);*/
Student stu1 = new Student(22,"aaa");
Student stu2 = new Student(55,"bbb");
Student stu3 = new Student(33,"ccc");
Student stu4 = new Student(11,"ddd");
List<Student> list3 = new ArrayList<Student>();
list3.add(stu1);
list3.add(stu2);
list3.add(stu3);
list3.add(stu4);
Collections.sort(list3);
System.out.println(list3);
}
}