Android collection usage finishing

Android collection usage finishing

The Java Collections Framework is an architecture that includes a set of interfaces and classes for the definition, operation, and management of collections provided by Java.
 
The basic interface/class hierarchy of the Java collection framework:

java.util.Collection [I]
+--java.util.List [I]
   +--java.util.ArrayList [C]
   +--java.util.LinkedList [C]
   +--java.util.Vector [ C]
      +--java.util.Stack [C]
+--java.util.Set [I]
   +--java.util.HashSet [C]
   +--java.util.SortedSet [I]
      +--java .util.TreeSet [C]

java.util.Map [I]
+--java.util.SortedMap [I]
   +--java.util.TreeMap [C]
+--java.util.Hashtable [C]
+--java.util.HashMap [ C]
+--java.util.LinkedHashMap [C]
+--java.util.WeakHashMap [C]
 
[I]: Interface
[C]: Class
 
Collection interface
    Collection is the most basic collection interface. A Collection represents a collection of a group of Objects. These Objects are called collection elements.
    All classes that implement the Collection interface must provide two standard constructors: a constructor with no parameters is used to create an empty Collection, and a constructor with a Collection parameter is used to create a new Collection. The incoming Collection has the same elements. The latter constructor allows the user to copy a Collection.
    How to traverse each element in the Collection? Regardless of the actual type of the Collection, it supports an iterator() method, which returns an iterator, which can be used to access each element in the Collection one by one. The typical usage is as follows:
Iterator it = collection.iterator(); //   
while(it.hasNext()) { 
 Object obj = it.next(); //   
}  
    According to different purposes, Collection is divided into List and Set.
 
List interface
    List inherits from Collection interface. List is an ordered Collection, using this interface can precisely control the position of each element inserted. The user can use the index (the position of the element in the List, similar to the array subscript) to access the elements in the List, which is similar to the Java array.
    Unlike the Set collection, the List allows duplicate elements. For the e1 and e2 object elements that meet the condition of e1.equals(e2), they can exist in the List collection at the same time. Of course, there are also implementation classes of List that do not allow duplicate elements.
    In addition to the iterator() method necessary for the Collection interface, List also provides a listIterator() method, which returns a ListIterator interface. Compared with the standard Iterator interface, ListIterator has more methods such as add(), allowing you to add them. Delete, set elements, and traverse forward or backward.
    Commonly used classes that implement the List interface are LinkedList, ArrayList, Vector, and Stack.
 
LinkedList class
    LinkedList implements the List interface and allows null elements. In addition, LinkedList provides additional get, remove, and insert methods at the head or tail of LinkedList. These operations enable LinkedList to be used as a stack, queue, or deque.
    Note that LinkedList has no synchronization method. If multiple threads access a List at the same time, they must implement access synchronization by themselves. One solution is to construct a synchronized List when creating the List:
List list = Collections.synchronizedList(new LinkedList(...));  
 
ArrayList class
    ArrayList implements variable-size arrays. It allows all elements, including null. The ArrayList is not synchronized.
The running time of the size, isEmpty, get, and set methods is constant. However, the cost of the add method is constant, and it takes O(n) time to add n elements. The running time of other methods is linear.
    Each ArrayList instance has a capacity (Capacity), that is, the size of the array used to store elements. This capacity can be automatically increased as new elements are continuously added, but the growth algorithm is not defined. When you need to insert a large number of elements, you can call the ensureCapacity method before inserting to increase the capacity of the ArrayList to improve insertion efficiency.
    Like LinkedList, ArrayList is also unsynchronized.
 
Vector class
    Vector is very similar to ArrayList, but Vector is synchronous. Although the Iterator created by Vector has the same interface as the Iterator created by ArrayList, because Vector is synchronized, when an Iterator is created and is being used, another thread changes the state of Vector (for example, adding or deleting some Element), when the Iterator method is called, ConcurrentModificationException will be thrown, so the exception must be caught.
 
Stack class
    Stack inherits from Vector and implements a last-in first-out stack. Stack provides 5 additional methods to enable Vector to be used as a stack. The basic push and pop methods, as well as the peek method to get the top element of the stack, the empty method tests whether the stack is empty, and the search method detects the position of an element in the stack. The stack is empty just after it is created.
 
Set interface
    Set inherits from the Collection interface. Set is a collection that cannot contain repeated elements, that is, for e1 and e2 object elements that meet the condition of e1.equals(e2), they cannot exist in the same Set collection at the same time, in other words, any two elements in the Set collection Both e1 and e2 satisfy the condition of e1.equals(e2) == false, and Set has at most one null element.
     Because of this restriction of Set, when using Set collection, you should pay attention to:
    1. Implement an effective equals(Object) method for the implementation class of the elements in the Set collection.
    2. For the Set constructor, the collection parameter passed in cannot contain duplicate elements.
 
    Please note: You must be careful with Mutable Objects. If a variable element in a Set changes its state and causes Object.equals(Object)=true, it will cause some problems.
 
HashSet class
    This class implements the Set interface and is supported by a hash table (actually a HashMap instance). It does not guarantee the iteration order of the collection; in particular, it does not guarantee that the order will last forever. This class allows the use of null elements.
    HashSet is not synchronized, you need to use the following statement to perform S synchronization conversion:
            Set s = Collections.synchronizedSet(new HashSet(...));
 
Map interface
    Map does not inherit the Collection interface. In other words, Map and Collection are two different collections. Collection can be seen as a collection of (value), and Map can be seen as a collection of (key, value).
    The Map interface provides three types of collection views from the content of the Map, a set of key sets, a set of value sets, or a set of key-value mapping relationships.
 
Hashtable class
    Hashtable inherits the Map interface and implements a hash table of key-value mapping. Any non-null object can be used as a key or value.
    Use put(key, value) to add data, and get(key) to retrieve data. The time overhead of these two basic operations is constant.
Hashtable adjusts performance through two parameters, initial capacity and load factor. Usually the default load factor of 0.75 achieves a good balance of time and space. Increasing the load factor can save space but the corresponding search time will increase, which will affect operations like get and put.
A simple example of using Hashtable is as follows. Put 1, 2, and 3 in Hashtable, and their keys are "one", "two", and "three" respectively:
Hashtable numbers = new Hashtable(); 
numbers.put("one", new Integer(1)); 
numbers.put("two", new Integer(2)); 
numbers.put("three", new Integer(3));  
To retrieve a number, such as 2, use the corresponding key:
Integer n = (Integer)numbers.get("two"); 
System.out.println("two =" + n);  
    Since the object as the key will determine the location of the corresponding value by calculating its hash function, any object as the key must implement the hashCode and equals methods. The hashCode and equals methods inherit from the root class Object. If you use a custom class as the key, be very careful. According to the definition of the hash function, if the two objects are the same, that is, obj1.equals(obj2)=true, then Their hashCode must be the same, but if the two objects are different, their hashCode is not necessarily different. If the hashCode of two different objects is the same, this phenomenon is called a conflict. The conflict will increase the time cost of operating the hash table. So try to define a good hashCode() method to speed up the operation of the hash table.
    If the same object has different hashCodes, the operation of the hash table will have unexpected results (the expected get method returns null). To avoid this problem, you only need to keep one thing in mind: you must duplicate the equals method and the hashCode method at the same time. Don t just write one of them.
    Hashtable is synchronized.
 
HashMap class
    HashMap is similar to Hashtable. The difference is that HashMap is asynchronous and allows null, that is, null value and null key. , But when HashMap is regarded as Collection (values() method can return Collection), the time cost of iterative sub-operation is proportional to the capacity of HashMap. Therefore, if the performance of the iterative operation is very important, do not set the initial capacity of the HashMap too high or the load factor too low.
 
WeakHashMap class
    WeakHashMap is an improved HashMap, which implements a "weak reference" to the key. If a key is no longer externally referenced, the key can be recycled by the GC.
 
Tools for collection operations
    Java provides java.util.Collections and java.util.Arrays classes to simplify the operation of collections
    java.util.Collections mainly provides some static methods to manipulate or create collections such as Collection and Map.
    java.util.Arrays mainly provides static methods to manipulate arrays. .
 
summary
    If it involves stack, queue and other operations, you should consider using List. For quick insertion and deletion of elements, you should use LinkedList. If you need to quickly and randomly access elements, you should use ArrayList.
    If the program is in a single-threaded environment, or the access is only performed in one thread, consider non-synchronized classes, which are more efficient. If multiple threads may operate a class at the same time, synchronized classes should be used.
    Except for using TreeSet and TreeMap when sorting is required, HashSet and HashMap should be used because they are more efficient.
    Special attention should be paid to the operation of the hash table, and the equals and hashCode methods should be correctly copied as the key object.
 
    The container class can only hold object references (pointers to objects), instead of copying the object information to a certain position in the sequence. Once the object is placed in the container, the type information of the object is lost.
    Try to return the interface instead of the actual type, such as returning List instead of ArrayList, so that if you need to change ArrayList to LinkedList in the future, the client code does not need to be changed. This is for abstract programming.
 
note:
1. Collection does not have a get() method to get an element. The elements can only be traversed through iterator().
2. Set and Collection have exactly the same interface.
3. List, one element at a time can be retrieved through the get() method. Use numbers to select one of a bunch of objects, get(0).... (add/get)
4. Generally use ArrayList. Use LinkedList to construct stack stack and queue queue.
5. Map use put(k,v)/get(k), you can also use containsKey()/containsValue() to check whether it contains a certain key/value.
      HashMap will use the hashCode of the object to quickly find the key.
 
6. For elements in Map, key sequence and value sequence can be extracted separately.
Use keySet() to extract the key sequence and generate a Set for all the keys in the map.
Use values() to extract the value sequence and generate a Collection of all the values in the map.
Why one generates Set and the other generates Collection? That's because the key is always unique, and the value is allowed to be repeated.
 
------------------------
This article is a combination of several online articles and excerpts: