ArrayList or. LinkedList or. Vecto

ArrayList is implemented as a resizable array. As more elements are added to ArrayList, its size is increased dynamically. It's elements can be accessed directly by using the get and set methods, since ArrayList is essentially an array.

LinkedList is implemented as a double linked list. Its performance on add and remove is better than Arraylist, but worse on get and set methods.

Vector is similar with ArrayList, but it is synchronized.

ArrayList is a better choice if your program is thread-safe. Vector and ArrayList require more space as more elements are added. Vector each time doubles its array size, while ArrayList grow 50% of its size each time. LinkedList, however, also implements Queue interface which adds more methods than ArrayList and Vector, such as offer(), peek(), poll(), etc.

ArrayList example

 1 ArrayList<Integer> al = new ArrayList<Integer>();
 2 al.add(3);
 3 al.add(2);        
 4 al.add(1);
 5 al.add(4);
 6 al.add(5);
 7 al.add(6);
 8 al.add(6);
 9  
10 Iterator<Integer> iter1 = al.iterator();
11 while(iter1.hasNext()){
12     System.out.println(iter1.next());
13 }

LinkedList example

 1 LinkedList<Integer> ll = new LinkedList<Integer>();
 2 ll.add(3);
 3 ll.add(2);        
 4 ll.add(1);
 5 ll.add(4);
 6 ll.add(5);
 7 ll.add(6);
 8 ll.add(6);
 9  
10 Iterator<Integer> iter2 = ll.iterator();
11 while(iter2.hasNext()){
12     System.out.println(iter2.next());
13 }

Note: The default initial capacity of an ArrayList is pretty small. It is a good habit to construct the ArrayList with a higher initial capacity. This can avoid the resizing cost.

posted @ 2015-06-17 22:11  Slowd  阅读(158)  评论(0编辑  收藏  举报