Java foundation of Colloction

0 Preface

  The following is an introduction to Java collection classes, as well as the corresponding use of each class, at the same time comparing the different characteristics of collections to make us understand.

1 Collction Interface

  • Collection is the most basic set of interfaces, a Collection represents a group of Object, i.e. Collection element (Elements).
  • How to traverse each element Collction in? Using an iterator iterator, with reference to the following codes
. 1 the Iterator collection.iterator IT = (); // get an iterator 
2  the while (it.hasNext ()) {
 . 3       Object obj = it.next (); // get the next element 
4 }
View Code

1.1 List Interface

  • List is ordered Collection , use this interface to precisely control the inserted location of each element. Users can use index (List elements in the position, similar to the array subscript) to access elements in the List, which is similar to an array of Java.
  • Collection iterator addition to the necessary interface () method, List also provides a listIterator () method returns a ListIterator interface and standard Iterator interface compared, a few more ListIterator add () method or the like, allows to add, delete, set elements, but also traversing forward or backward.
  • List interfaces to achieve common class of LinkedList, ArrayList, Vector, and Stack.

1.1.1 LinkList class

  • LinkedList implements List interface that allows null elements. In addition to provide additional LinkedList get, remove, insert method. LinkedList these operations may be used as a stack (stack), a queue (Queue) or double-ended queue (deque).
  • Note that no synchronization LinkedList . If multiple threads access a LinkedList, they must implement their own access synchronization. Another solution is to construct a synchronization when creating List of List: List list = Collections.synchronizedList (new

1.1.2 ArrayList class

  • ArrayList implements an array of variable size. It allows all the elements, including null. ArrayList is no synchronization.
  • size, isEmpty, get, set method of running time is constant. But add methods for the assessment of a constant, add n elements need to O (n) time. Other methods running time is linear.
  • Each ArrayList instance has a capacity (Capacity), i.e., for the size of the array elements stored. With the capacity to add new elements to increase automatically, but growth algorithm is not defined. When the need to insert a large number of elements, the insert can be called ensureCapacity ArrayList method to increase the capacity to improve the efficiency of insertion.

1.1.3 Vector class

  Vector is very similar to the ArrayList, but Vector is synchronized. Created by Vector Iterator, although ArrayList created Iterator is the same interface, but because Vector is synchronized, when a Iterator been created and is being used by another thread Vector change the status of (for example, add or delete some element), then call when the method Iterator will throw ConcurrentModificationException, it is necessary to catch the exception.  

1.1.4 Stack class

  Stack inherited from Vector, to implement a LIFO stack. Stack provide five additional approach allows Vector to be used as a stack. Basic push and pop methods, there are peek method to obtain the element stack, empty method to test whether the stack is empty, Search method for detecting the position of an element in the stack. Stack after stack is empty just created.

Vector, ArrayList and LinkedList compare

  1. Vector is thread synchronization, so it is thread-safe, but ArrayList and LinkedList not thread-safe . If you do not take into account safety factors threads, usually with ArrayList and LinkedList more efficient.
  2. ArrayList and Vector data structure is implemented based on dynamic array, LinkedList based linked list data structure.
  3. If the number of elements of the set current set greater than the length of the array, Vector current growth rate of 100% of the length of the array, and ArrayList current growth rate of 50% of the length of the array. Conversely, there are advantages with the ArrayList; If a large amount of data in the data set, with a vector has certain advantages.
  4. If the lookup data in a specified location, time and ArrayList Vector used is the same, it takes time O (1), and find the need to traverse LinkedList, it takes time O (i), less efficient than the former two.
  5. If moving, deleting time data spent in a specified position is 0 (ni) n is the total length, this time should consider using the LinkedList, because of the time it is moved a specified data location takes 0 (1).
  6. For the specified location insertion data, LinedList comparative advantage, because ArrayList to move data.

1.2 Set category

  • Set does not contain a repeat element Collection , i.e., any two elements e1 and e2 are e1.equals (e2) = false, Set up to a null element.
  • Clearly, there is a Set constructor constraint, the incoming Collection parameter can not contain duplicate elements.

1.3 Map class

  No successor Map Collection interface , Map provide the key to value mapping. Map can not contain the same key, each key can map a value.

  Map interface provides three kinds of pools view, Map content can be set as a key group, a group set value, or a set of key-value mappings.

1.3.1 Hastable class

  • Hashtable inherited Map interface, the hash table a key-value mapping. Any object of non-empty (non-null) can be used as a key or value .
  • Add data using put (key, value), using the extracted data get (key), the two basic operation time overhead is constant.
  • Hashtable adjusted through initial capacity and load factor two parameters. Usually the default load factor 0.75 better achieved the balance of time and space. Increasing the load factor can save space but find the corresponding time will increase, which will affect operations such as get and put.
  • Since the object as a key to determine the location of the corresponding value calculated by the hash function, so any object as a key must implement equals and hashCode method. equals and hashCode method inherited from the root class Object.
  • Hashtable is synchronized, thread-safe .

1.3.2 HashMap class

  Hashtable HashMap and the like, except that the HashMap non-synchronized , and allow null, null value and Key null . However, when the HashMap considered Collection (values () method returns the Collection), which is proportional to the capacity of the iterator operation time expenses and HashMap. Therefore, if the performance of iterative important operation, it will not HashMap initialization for the high capacity, or load factor too low.  

2 summary

  • If it comes to operating stacks, queues, etc., should consider the use of List; the need to quickly insert, delete elements, you should use LinkedList; if you need fast random access to elements, you should use ArrayList.
  • If the program, or to access only in a thread in a single-threaded environment, consider the asynchronous type, high efficiency; if multiple threads may simultaneously operate a class, the class should be used to synchronize.
  • Pay special attention to the operation of the hash table, as a key target to correct replication equals and hashCode methods.
  • When using the Map, retrieve, update, delete, or add the best use HashMap HashTable; when the natural order of the Map, or a custom key sequence to traverse, it is best to use TreeMap;
  • Try to return to the interface instead of the actual type, such as return List rather than ArrayList, so that if you later need to be replaced ArrayList LinkedList, client code need not change. This is for the abstract programming.
  • ArrayList / LinkedList , Hashet / LinkedHashSet is thread safe. You can use the synchronized keyword.
  • LinkedList support for the insertion of header and trailer, but inherited from the Collection interface add () method is to insert in the tail.

Several questions 3 interview

1.Q: ArrayList and Vector What is the difference? HashMap and HashTable What is the difference?

   A: the Vector and HashTable is (synchronized), that is thread-safe thread synchronization. Performance, ArrayList and HashMap are better than Vector and Hashtable.

2.Q: roughly explain the architecture java collection of
   A: List, Set, Map is this collection system in three main interfaces.
      Which inherited from the Collection List and Set interfaces.
      Set does not allow duplicate elements. HashSet and TreeSet are two main implementation class.
     List orderly and allows duplicate elements. ArrayList, LinkedList and Vector are three main implementation class.
      Map also belongs to the set system, but different interfaces and Collection. Map is a key set of value mappings, where the key columns are a collection. key can not be repeated, but the value can be repeated. HashMap, TreeMap and Hashtable are three main implementation class.
      Sort SortedSet and SortedMap interface elements specified rules, SortedMap is a key column is sorted.

3.Q: Comparable and Comparator difference
    A: call java.util.Collections.sort (List list) method to sort the time, Object within the List must implement the Comparable interface.
        java.util.Collections.sort (List list, Comparator c) , may temporarily declare a Comparator to achieve the sort.

Guess you like

Origin www.cnblogs.com/huanghzm/p/11019994.html