1》,集合纯数字排序。
public static void main(String[] args) {
/*List<String> list = new ArrayList<>();
list.add("one");
list.add("Word");
list.add("one");
list.add("Dream");*/
List<Integer> list = new ArrayList<>();
list.add(1);
list.add(5);
list.add(7);
list.add(12);
Collections.sort(list);
System.out.println(list);
}
2》。对象按年龄排序。
package com.huanruan.java;
public class Student implements Comparable<Student>{
private String id;
private String name;
private Integer age;
public Student() {
super();
}
public Student(String id, String name, Integer age) {
super();
this.id = id;
this.name = name;
this.age = age;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((age == null) ? 0 : age.hashCode());
result = prime * result + ((id == null) ? 0 : id.hashCode());
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
// return 10;
}
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Student other = (Student) obj;
if (age == null) {
if (other.age != null)
return false;
} else if (!age.equals(other.age))
return false;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
@Override
public String toString() {
return id +"\t\t"+ name+"\t\t" + age ;
}
@Override
public int compareTo(Student o) {
int i = this.getAge() - o.getAge();//先按照年龄排序
if(i == 0){
return this.age- o.getAge();//如果年龄相等了再用分数进行排序
}
return i;
}
}
public class test {
public static void main(String[] args) {
List<Student> list = new ArrayList();
Student student=new Student();
list.add(new Student("1001","tom",18));
list.add(new Student("1002","jack",20));
list.add(new Student("1003","rose",15));
list.add(new Student("1004","jerry",17));
Collections.sort(list);
System.out.println(list);
}
}