TreeMap
【小城贝尔】
底层红黑树,键值来相助。
左右类中笼,含父定黑红。
数据存入池,键将顺序执。
排序自定义,接口做膀臂。
TreeMap底层是红黑树
//TreeMap 源码
static final class Entry<K,V> implements Map.Entry<K,V> {
K key;
V value;
Entry<K,V> left;
Entry<K,V> right;
Entry<K,V> parent;
boolean color = BLACK;
public class TreeMapDemo {
public static void main(String[] args) {
TreeMap<Integer ,String > tm = new TreeMap<>();
tm.put(4,"尔");
tm.put(3,"贝");
tm.put(1,"小");
tm.put(2,"城");
System.out.println(tm);//{1=小, 2=城, 3=贝, 4=尔} key会排序
TreeMap<Student ,String> tr = new TreeMap<>();
tr.put(new Student(111,"guo",3000),"java");
tr.put(new Student(333,"li" ,1000),"is");
tr.put(new Student(333,"li" ,1000),"is");
tr.put(new Student(333,"li" ,2000),"is");
tr.put(new Student(333,"li" ,3000),"is");
tr.put(new Student(30,"cheng",5000),"good");
tr.put(new Student(500,"can" ,300),"very");
tr.put(new Student(999,"fly" ,1000),"nice");
System.out.println(tr);
}
}
class Student implements Comparable<Student>{
private Integer id;
private String name;
private Integer salary;
public Student(Integer id, String name, Integer salary) {
this.id = id;
this.name = name;
this.salary = salary;
}
@Override
public int compareTo(Student o) {
if(this.id > o.id){
return 1;
}else if(this.id <= o.id){
return -1;
}else if(this.salary > o.salary){
return 1;
}else if(this.salary <= o.salary){
return -1;
}
return 0;
}
@Override
public String toString() {
return "Student{" +
"id=" + id +
", name='" + name + '\'' +
", salary=" + salary +
'}';
}
}