HashSet的查询效率比数组高?
回家比较晚,我重新说一下吧,其实就几个要点
1.仔细看了下上面的代码应该是TreeMap的,不是HashSet(我没有证实过,需要求证答主,很大可能是错了)
2.关于是否有序这个问题,HashMap的链表结构天生决定了无须
3.HashSet底层是否是树结构,其实就是研究HashMap底层的结构,1.8以前是链表,1.8改为了 当阈值大于一定数量时,底层结构变为红黑树结构
4.还是那概念,有序和无序不是决定集合效率的标准,关键在于结构和算法
5.学习知识重在理解,不要太急于求成
hashSet可以做成有序的,,(也就是插入时他会自己排序,下面有hashset的源码)
数组是无序的,,有序的当然要比无序的查起来快了。。
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;
// split comparator and comparable paths
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();
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;
}
看不懂没关系,,我把排序的哪一段挑出来了如下,,大概知道就行:
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);
hashset是不保证有序的,查询快慢和有序无序没有本质联系,在于各自的数据模型和算法。hashset是根据hash算法实现的,数组是简单的数据结构,导致了两个模型查找时的时间复杂度是不同的。
一般情况下,仅仅是一般情况,无序的数据结构采用的算法效率时由于有序结构的(仅仅是一般的开发情况,我感觉题主的情况是这个)
谢谢你,貌似明白了,HashSet底层用的是树结构么?