ArrayList与LinkedList、TreeSet与HashSet、HashMap与LinkedHashMap之间的比较

来源:互联网 发布:网络文凭有用吗 编辑:程序博客网 时间:2024/06/05 02:21

前言:人类思考,上帝就发笑


之前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的key2. Map的key和Set都有一个共同的特性就是集合的唯一性.TreeMap更是多了一个排序的功能.3. hashCode和equal()是HashMap用的, 因为无需排序所以只需要关注定位和唯一性即可.   a. hashCode是用来计算hash值的,hash值是用来确定hash表索引的.   b. hash表中的一个索引处存放的是一张链表, 所以还要通过equal方法循环比较链上的每一个对象       才可以真正定位到键值对应的Entry.   c. put时,如果hash表中没定位到,就在链表前加一个Entry,如果定位到了,则更换Entry中的value,并返回旧value4. 由于TreeMap需要排序,所以需要一个Comparator为键值进行大小比较.当然也是用Comparator定位的.   a. Comparator可以在创建TreeMap时指定   b. 如果创建时没有确定,那么就会使用key.compareTo()方法,这就要求key必须实现Comparable接口.   c. TreeMap是使用Tree数据结构实现的,所以使用compare接口就可以完成定位了.
我们下面来看个例子(HashSet使用):
import java.util.HashSet;import java.util.Iterator;public class WpsklHashSet{//java 中Set的使用(不允许有重复的对象):public static void main(String[] args){  HashSet hashSet=new HashSet();  String a=new String("A");  String b=new String("B");  String c=new String("B");  hashSet.add(a);  hashSet.add(b);  System.out.println(hashSet.size());  String cz=hashSet.add(c)?"此对象不存在":"已经存在";  System.out.println("测试是否可以添加对象    "+cz);  System.out.println(hashSet.isEmpty());  //测试其中是否已经包含某个对象  System.out.println(hashSet.contains("A"));  Iterator ir=hashSet.iterator();  while(ir.hasNext())  {   System.out.println(ir.next());  }  //测试某个对象是否可以删除  System.out.println(hashSet.remove("a"));  System.out.println(hashSet.remove("A"));  //经过测试,如果你想再次使用ir变量,必须重新更新以下  ir=hashSet.iterator();  while(ir.hasNext())  {   System.out.println(ir.next());  }}}/** * 通过这个程序,还可以测试树集的添加元素的无序性与输出的有序性 */ import java.util.TreeSet;import java.util.Iterator;public class TreeSetTest{    public static void main(String[] args)    {        TreeSet tree = new TreeSet();        tree.add("China");        tree.add("America");        tree.add("Japan");        tree.add("Chinese");                Iterator iter = tree.iterator();        while(iter.hasNext())        {            System.out.println(iter.next());        }    }}

我们可以总结如下:
HashSet无序
TreeSet有序
二者里边不能有重复的对象
3.HashMap与LinkedHashMap比较
HashMap底层是hashCode算法结构。    LinkedHashMap底层是链表结构。    如果要不确定位置增、删的话LinkedHashMap比较快。    如果确定位置增加、查询的话那么HashMap比较快。    LinkedHashMap可以实现快速的查询第一个元素(First)跟结尾(Last)



0 0
原创粉丝点击