本文是对高淇版Java三百集,TreeMap和HashTable内容学习的记录。一般在需要排序的Map时才使用TreeMap。
TreeMap底层是一个红黑树,它是一个红黑二叉树的典型实现。就调用者来说,它的用法和HashMap几乎没有任何区别,HashMap效率高于TreeMap
一、TreeMap常用方法
1.1 put()方法
public V put(K key, V value)
1.2 get()方法
public V get(Object key)
1.3 remove()方法
public V remove(Object key)
1.4 TreeMap功能测试
值得一提的是,这里的Comparable接口。实现Comparable接口,需要实现该接口中唯一的compareTo()方法,来指定Employe类中的排序规则。在TreeMap源码中有调用compareTo()方法,进而实现TreeMap的排序功能。
package cn.edu.ucas.gqlearn;
import java.util.Collection;
import java.util.Collections;
import java.util.Map;
import java.util.TreeMap;
/**
* @Author: hyk
* @Date: 2020/7/22
* @version: 1.0
*/
public class TestTreeMap {
public static void main(String[] args) {
Map<Integer,String> map = new TreeMap<>();
map.put(1002,"刘亦菲");
map.put(1001,"赵丽颖");
map.put(1003,"杨幂");
System.out.println(map.toString());
Employee employee1 = new Employee(01,"小one",15000);
Employee employee2 = new Employee(03,"小two",17000);
Employee employee3 = new Employee(02,"小three",16000);
Map<Employee,String> map1 = new TreeMap<>();
map1.put(employee1,"这是小one!");
map1.put(employee2,"这是小two!");
map1.put(employee3,"这是小three!");
System.out.println(map1.toString());
}
}
class Employee implements Comparable<Employee>{
int id;
String name;
double salary;
public Employee() {
}
public Employee(int id, String name, double salary) {
this.id = id;
this.name = name;
this.salary = salary;
}
@Override
public String toString() {
return "Employee{" +
"id=" + id +
", Name='" + name + '\'' +
", Salary=" + salary +
'}';
}
@Override
public int compareTo(Employee o) {
if (this.salary > o.salary){
return 1;
}else if(this.salary < o.salary){
return -1;
}else{
if (this.id > o.id){
return 1;
}else if(this.id < o.id){
return -1;
}else{
return 0;
}
}
}
}
二、HashTable类
关于HashTable,先抽象的记录两点,日后补充。