public static void main(String [] args){
/*
源码分析:
1.继承关系
class TreeMap<K,V>extends AbstractMap<K,V> implements NavigableMap<K,V>, Cloneable, java.io.Serializable
2.构造器
无参构造器
public TreeMap() {
comparator = null;
}
3.底层数据结构:
二叉树(红黑树)
因为红黑树的插入顺序是根据中序遍历插入的,因此对于自定义的类需要实现内部比较器或者外部比较器
*/
TreeMap<String,Integer> treeMap=new TreeMap<String, Integer>();
treeMap.put("ls",12);
treeMap.put("zs",18);
treeMap.put("zs",19);
//ls :12
//zs :19
/*
从遍历结果可以看出,
public V put(K key, V value) {
Entry<K,V> t = root;//标记根节点,从根节点开始遍历插入
if (t == null) {//说明当前还没有存储数据
compare(key, key); // type (and possibly null) check
root = new Entry<>(key, value, null);//将第一个节点作为根节点
size = 1;
modCount++;
return null;
}
int cmp;
Entry<K,V> parent;//说明存在根节点,将根节点给标记,然后遍历,parent小的继续遍历左边的分支,比parent大的继续遍历右边的分支
Comparator<? super K> cpr = comparator;
if (cpr != null) {
do {
parent = t;
cmp = cpr.compare(key, t.key);
if (cmp < 0)
t = t.left;
else if (cmp > 0)
t = t.right;
else
return t.setValue(value);
} while (t != null);
}
else {
if (key == null)
throw new NullPointerException();
@SuppressWarnings("unchecked")
Comparable<? super K> k = (Comparable<? super K>) key;
do {
parent = t;
cmp = k.compareTo(t.key);
if (cmp < 0)
t = t.left;
else if (cmp > 0)
t = t.right;
else
return t.setValue(value);
} while (t != null);
}
Entry<K,V> e = new Entry<>(key, value, parent);
if (cmp < 0)
parent.left = e;
else
parent.right = e;
fixAfterInsertion(e);
size++;
modCount++;
return null;
}
*/
Set<Map.Entry<String, Integer>> entries = treeMap.entrySet();
Iterator<Map.Entry<String, Integer>> iterator = entries.iterator();
while (iterator.hasNext()){
Map.Entry<String, Integer> next = iterator.next();
System.out.print(next.getKey()+" :"+next.getValue());
System.out.println ();
}
//对值得遍历
Collection<Integer> values = treeMap.values();
Iterator<Integer> iterator1 = values.iterator();
while (iterator1.hasNext()){
Integer next = iterator1.next();
System.out.println(next);
}
Set<String> strings = treeMap.keySet();
Iterator<String> iterator2 = strings.iterator();
while (iterator2.hasNext()){
String next = iterator2.next();
System.out.println(next);
}
}