用于排序
public static void main(String[] args) {
// TODO Auto-generated method stub
//基本类型已经实现了该接口,可以直接使用
ArrayList<Integer> a=new ArrayList<>();
a.add(3);
a.add(4);
a.add(1);
Collections.sort(a);
for(Integer b:a){
System.out.print(b+" ");
}
ArrayList<String> c=new ArrayList<>();
c.add("abc");
c.add("Dts");
c.add("acd");
Collections.sort(c);
for(String d:c){
System.out.print(d+" ");
}
int[] e=new int[]{1,4,4,5,2,4,6};
Arrays.sort(e);
for(Integer f:e){
System.out.print(f+" ");
}
//自己写的类需要继承接口Comparable
ArrayList<Person> persons=new ArrayList<>();
Person person=new Person(32,"张三",14);
persons.add(person);
person=new Person(14,"李四",25);
persons.add(person);
person=new Person(10,"王五",145);
persons.add(person);
Collections.sort(persons);
for(Person myperson:persons){
System.out.println(myperson);
}
}
public class Person implements Comparable<Person>{
private int id;
private String name;
private int age;
public Person(int id,String name,int age){
this.id=id;
this.name=name;
this.age=age;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public int compareTo(Person person) {
// TODO Auto-generated method stub
return id-person.getId();
}
@Override
public String toString(){
StringBuilder s=new StringBuilder();
s.append(id);
s.append(",");
s.append(name);
s.append(",");
s.append(age);
return s.toString();
}
}