treemap
treeMap
类需要实现comparable
需要重写compareTo
import java.util.TreeMap;
public class Demo01 {
public static void main(String[] args) {
//创建集合
TreeMap treeMap = new TreeMap<>();
//1添加元素
Student s1 = new Student("孙悟空", 01);
Student s2 = new Student("猪八戒", 02);
Student s3 = new Student("沙和尚", 03);
treeMap.put(s1, "北京");
treeMap.put(s2, "上海");
treeMap.put(s3, "北京");
System.out.println(treeMap);
}
}
package Collection.Map.Demo03;
import java.util.Objects;
public class Student implements Comparable {
private String name;
private int stuNo;
public Student() {
}
public Student(String name, int stuNo) {
this.name = name;
this.stuNo = stuNo;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getStuNo() {
return stuNo;
}
public void setStuNo(int stuNo) {
this.stuNo = stuNo;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", stuNo=" + stuNo +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Student)) return false;
Student student = (Student) o;
return getStuNo() == student.getStuNo() && Objects.equals(getName(), student.getName());
}
@Override
public int hashCode() {
return Objects.hash(getName(), getStuNo());
}
@Override
public int compareTo(Student o) {
//int n1 = this.name.compareTo(o.getName());
int n2 = this.stuNo-o.stuNo;
return n2;
}
}