ArrayList与LinkedList、TreeSet与HashSet、HashMap与LinkedHashMap之间的比较
之前ArrayList与LinkedList、TreeSet与HashSet、HashMap与LinkedHashMap之间都比较茫然,下面我针对这
几个类具体类来进行比较,首先我们上一张图
在上面的比较中,我们针对相同颜色的俩者分别来进行比较
1.ArrayList与LinkedList比较
ArrayList 采用的是数组形式来保存对象的,这种方式将对象放在连续的位置中,所以最大的缺点就是插入删除时非常麻烦
LinkedList 采用的将对象存放在独立的空间中,而且在每个空间中还保存下一个链接的索引 但是缺点就是查找非常麻烦 要丛第一个索引开始
你可以把 ArrayList看做是一个大小长度可变的数组来使用~~~ 一般情况也常用这个做查询操作;
LinkedList呢 他其实是一种链表形式的容器,插入删除很方便
以下是他们大体的图形:
ArrayList:
【】【】【】【】【】【】【】【】
他就是一个数组的形状;
LinkedList:
【】
_【】
__【】
___【】
他就是一个链表形状:从这个图中你也应该可以看出为什么他删除,添加插入比较方便了吧
2.TreeSet和HashSet的比较
1. HashSet是通过HashMap实现的,TreeSet是通过TreeMap实现的,只不过Set用的只是Map的key
2. Map的key和Set都有一个共同的特性就是集合的唯一性.TreeMap更是多了一个排序的功能.
3. hashCode和equal()是HashMap用的, 因为无需排序所以只需要关注定位和唯一性即可.
a. hashCode是用来计算hash值的,hash值是用来确定hash表索引的.
b. hash表中的一个索引处存放的是一张链表, 所以还要通过equal方法循环比较链上的每一个对象
才可以真正定位到键值对应的Entry.
c. put时,如果hash表中没定位到,就在链表前加一个Entry,如果定位到了,则更换Entry中的value,并返回旧value
4. 由于TreeMap需要排序,所以需要一个Comparator为键值进行大小比较.当然也是用Comparator定位的.
a. Comparator可以在创建TreeMap时指定
b. 如果创建时没有确定,那么就会使用key.compareTo()方法,这就要求key必须实现Comparable接口.
c. TreeMap是使用Tree数据结构实现的,所以使用compare接口就可以完成定位了.
我们下面来看个例子(HashSet使用):
我们可以总结如下:
HashSet无序
TreeSet有序
二者里边不能有重复的对象
3.HashMap与LinkedHashMap比较
HashMap底层是hashCode算法结构。
LinkedHashMap底层是链表结构。
如果要不确定位置增、删的话LinkedHashMap比较快。
如果确定位置增加、查询的话那么HashMap比较快。
LinkedHashMap可以实现快速的查询第一个元素(First)跟结尾(Last)