TreeSet与TreeMap的关系: 1.TreeSet 实际上就是用TreeMap来组织数据的,因为在TreeSet中保存了一个NavigableMap<e,Object>接口实例变量,而该接口的实现类就是TreeMap 2.TreeSet与Tree ...
TreeSet与TreeMap的关系:
1.TreeSet 实际上就是用TreeMap来组织数据的,因为在TreeSet中保存了一个NavigableMap<e,Object>接口实例变量,而该接口的实现类就是TreeMap
2.TreeSet与TreeMap都是用二叉树的数据结构来存储数据
3.TreeSet和TreeMap中保存的数据除了Integer和String等有默认顺序的类型外的自定义类型都需要实现Comparable接口并重写compareTo()方法。
TreeSet和TreeMap添加数据:
TreeSet的add方**调用TreeMap的put方法
TreeMap的put()方法的实现,
public V put(K key, V value) { Entry<K,V> t = root; //判断二叉树中是否存在根节点如果存在则床建根节点 if (t == null) { root = new Entry<K,V>(key, value, null);//创建根节点 size = 1;//将该集合的元素个数设为1 modCount++; return null; } int cmp; Entry<K,V> parent;//声明父节点 Comparator<? super K> cpr = comparator;//创建比较器 if (cpr != null) {//该集合有自定义比较器 do { parent = t;//将父节点设为t (第一次t为根节点) cmp = cpr.compare(key, t.key);//将根节点的key与参数中的key进行比较 if (cmp < 0)//key<t.key t = t.left; else if (cmp > 0)//key>t.key t = t.right; else return t.setValue(value);//key==t.key } while (t != null); } else {//该集合没有自定义比较器 if (key == null) throw new NullPointerException(); Comparable<? super K> k = (Comparable<? super K>) key;//参数使用类型的比较器 do { parent = t;//将父节点设为t (第一次t为根节点) cmp = k.compareTo(t.key);//将根节点的key与参数中的key进行比较 if (cmp < 0)//key<t.key t = t.left; else if (cmp > 0)//key>t.key t = t.right; else return t.setValue(value);;//key==t.key } while (t != null); } Entry<K,V> e = new Entry<K,V>(key, value, parent);//将传入的参数封装为集合元素 if (cmp < 0)//e<parent parent.left = e; else //e>parent parent.right = e; fixAfterInsertion(e); size++; modCount++; return null;}
海外公司注册、海外银行开户、跨境平台代入驻、VAT、EPR等知识和在线办理:https://www.xlkjsw.com
原标题:TreeSet与TreeMap浅解
关键词:
*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们:
admin#shaoqun.com
(#换成@)。