package Test;
import java.util.Map;
import java.util.TreeMap;
/**
* TreeMap的使用和底层实现
* TreeMap是红黑二叉树的典型实现。我们打开TreeMap的源码,发现有一行核心代码:
* private transient Entry<K,V> root=null;
* root用来存储整个树的根节点。我们继续跟踪Entry(是TreeMap的内部类)的代码:
* static final class Entry<K,V> implements Map,Entry<K,V>{
* K key;
* V value;
* Entry<K,V> left=null;
* Entry<K,V> right=null;
* Entry<K,V> parent;
* boolean color=BLACK;
* }
* 可以看到里面存储了本身数据、左节点、右节点、父节点、以及节点颜色。
* TreeMap的put()/remove()方法大量使用了红黑树的理论。本书限于篇幅,不再展开。
* 需要了解更深入的,可以参考专门的数据结构书籍。
* TreeMap和HashMap实现了同样的接口Map,因此,用法对于调用这来说没有区别。
* HashMap效率高于TreeMap;
* 在需要排序的Map是才选用TreeMap.
*
*
*
* *****************
* HashMap和HashTable
* HashMap采用哈希算法实现,是Map接口最常用的实现类。由于底层采用了哈希表存储数据
* 我们要求键不能重复,如果发生重复,新的键值对会替换旧的键值对。
* HashMap在查找、删除、修改方面都有非常高的效率。
* HashTable类和HashMap用法几乎一样,底层实现几乎一样,只不过HashTable的方法添加了
* synchronized关键字确保线程同步检查,效率较低。
*
* HashMap与HashTable的区别
* 1.HashMap:线程不安全,效率高。允许key或value为null.
* 2.HashTable:线程安全,效率低。不允许key或value为null.
* *****************
* @author pmc
*
*/
public class TreeMapTest {
public static void main(String[] args){
Map<Integer,String> treemap=new TreeMap<Integer,String>();
treemap.put(20,"AA");
treemap.put(3,"BB");
treemap.put(6,"CC");
//按照key递增的方式排序
for(Integer temp:treemap.keySet()){
System.out.println(temp+"="+treemap.get(temp));
}
Map<Emp,String> treemap2=new TreeMap<Emp,String>();
treemap2.put(new Emp(101,"张三",50000), "一零一");
treemap2.put(new Emp(103,"李四",5000), "一零三");
treemap2.put(new Emp(102,"王五",500), "一零二");
treemap2.put(new Emp(104,"赵六",5000), "一零四");
for(Emp temp:treemap2.keySet()){
System.out.println(temp);
}
}
}
class Emp implements Comparable<Emp>{
int id;
String name;
double salary;
public Emp(int id, String name, double salary) {
super();
this.id = id;
this.name = name;
this.salary = salary;
}
@Override
//负数:小于,0:等于,正数:大于
public int compareTo(Emp 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;
}
}
}
@Override
public String toString() {
return "Emp [id=" + id + ", name=" + name + ", salary=" + salary + "]";
}
}