[Java Basics] Collection

Posted on 2014-08-13 22:43  chayu3  阅读(193)  评论(0编辑  收藏  举报

除了Java collection class/interface外,方便的有Google guava的utility class: Lists/Sets/Maps/Queues, 用它们可以方便地创建List等object。

List<String> list = Lists.newArrayList(); or Lists.newArrayList("1", "2");

ArrayList v.s. Vector:

两者都是implement了List interface,

ArrayList: Resizable-array implementation of the List interface. 

Vector: The Vector class implements a growable array of objects. 

两者的区别是: Vector synchronizes on each individual operation, 所以会很慢,最好用ArrayList。

ArrayList v.s. LinkedList:

LinkedList implements it with a doubly-linked list. ArrayList implements it with a dynamically resizing array.

LinkedList<E> allows for constant-time insertions or removals using iterators, but only sequential access of elements.

ArrayList<E>, on the other hand, allow fast random read access, so you can grab any element in constant time. But adding or removing from anywhere but the end requires shifting all the latter elements over, either to make an opening or fill the gap. 

ConcurrentHashMap v.s. HashMap v.s. Hashtable:

三者都是implement了Map interface,

ConcurrentHashMap: thread-safe, Instead of a map wide lock, the collection maintains a list of 16 locks by default, each of which is used to guard (or lock on) a single bucket of the map. This effectively means that 16 threads can modify the collection at a single time (as long as they’re all working on different buckets). http://www.codercorp.com/blog/java/why-concurrenthashmap-is-better-than-hashtable-and-just-as-good-hashmap.html

HashMap: allows null key/value, not thread-safe. LinkedHashMap reserves the inserting order. HashMap methods include: containsKey(), containsValue(), remove(key), put(key, value), isEmpty(), size(). Here put() will update old value.

Iterate HashMap: Set<K> keySet(); Collection<V> values(); Set<Map.Entry<K,V>> entrySet(); You can use for loop on each's result. Or you can also use .iterator().

Hashtable: not allows null key/value, thread-safe, Hashtable’s offer concurrent access to their entries, with a small caveat, the entire map is locked to perform any sort of operation. 

Collections.synchronizedHashMap(): use very simple synchronization, which means that only one thread can access the map at the same time.if you need to ensure data consistency, and each thread needs to have an up-to-date view of the map. While, Use the ConcurrentHashMap if performance is critical, and each thread only inserts data to the map, with reads happening less frequently.

复杂度HashMap: 理想情况下是O(1), 但如果出现所有key都产生了同样的hash的情况,那就得iterate所有elements来找到目标O(n).

Parent interface of Collection: Iterable Interface

A class that implements the Iterable can be used with the new for-loop. 

The Iterable interface has only one method:

public interface Iterable<T> {
  public Iterator<T> iterator();    
}

It is possible to use your own collection type classes with the new for-loop. To do so, your class must implement thejava.lang.Iterable<E> interface. Here is a very basic example:

public class MyCollection<E> implements Iterable<E>{

    public Iterator<E> iterator() {
        return new MyIterator<E>();
    }
}

And here is the corresponding implementation skeleton of the MyIterator class:

public class MyIterator <T> implements Iterator<T> {

    public boolean hasNext() {
    
        //implement...
    }

    public T next() {
        //implement...;
    }

    public void remove() {
        //implement... if supported.
    }
}

迭代器应用:
 list l = new ArrayList();
 l.add("aa");
 l.add("bb");
 l.add("cc");
 for (Iterator iter = l.iterator(); iter.hasNext();) {
  String str = (String)iter.next();
  System.out.println(str);
 }

 TreeSet & TreeMap

Both are sorted java data structures. Implementation is Red-Black tree. Time complexity for search/insert is O(logn).

HashSet: methods include add(), remove(), contains(), size(), isEmpty(). Here add() will return false if you are trying to add the same element.