The difference between Set, List, Map, Vector, ArrayList

 

https://blog.csdn.net/friends99/article/details/79757825

 

The difference between Set, List, Map, Vector, ArrayList

The container of JAVA-List, Map, Set 
Collection 
├List 
│├LinkedList 
│├ArrayList 
│└Vector 
│ └Stack 
└Set 
Map 
├Hashtable 
├HashMap 
└WeakHashMap

Collection interface 
  Collection is the most basic collection interface. A Collection represents a group of Objects, namely Elements of Collection. Some Collections allow the same elements while others do not. Some can be sorted while others cannot. The Java SDK does not provide classes that directly inherit from Collection. The classes provided by the Java SDK are all inherited from the "sub-interfaces" of Collection such as List and Set. 
  All classes that implement the Collection interface must provide two standard constructors: a parameterless constructor is used to create an empty Collection, and a constructor with a Collection parameter is used to create a new Collection. This new Collection and pass The imported Collection has the same elements. The latter constructor allows the user to copy a Collection. 
  How to traverse every element in Collection? Regardless of the actual type of the Collection, it supports an iterator () method, which returns an iterator, using this iterator to access each element in the Collection one by one. Typical usage is as follows: 
    Iterator it = collection.iterator (); // get an iterator 
    while (it.hasNext ()) {
      Object obj = it.next  (); // get the next element 
    } 
  derived from the Collection interface The two interfaces are List and Set.

List 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 mentioned below, List allows the same elements. 
  In addition to the iterator () method necessary for the Collection interface, List also provides a listIterator () method that returns a ListIterator interface. Compared with the standard Iterator interface, ListIterator has some more methods such as add (), which allows you to add Delete, set elements, and traverse forward or backward. 
  Common classes that implement the List interface are LinkedList, ArrayList, Vector, and Stack.

The LinkedList class 
  LinkedList implements the List interface, allowing null elements. In addition, LinkedList provides additional get, remove, and insert methods at the beginning or end of the LinkedList. These operations make LinkedList can be used as a stack (stack), queue (queue) or two-way queue (deque). 
  Note that LinkedList has no synchronization method. If multiple threads access a List at the same time, you must implement access synchronization yourself. One solution is to construct a synchronized List when creating the List: 
    List list = Collections.synchronizedList (new LinkedList (...));

The ArrayList class 
  ArrayList implements variable-size arrays. It allows all elements, including null. ArrayList is not synchronized. 
The running time of size, isEmpty, get, and set methods is constant. However, the cost of the add method is an amortized constant, and adding n elements takes O (n) time. The running time of other methods is linear. 
  Each ArrayList instance has a capacity, which is the size of the array used to store the elements. This capacity can automatically increase as new elements are added, but the growth algorithm is not defined. When a large number of elements need to be inserted, the ensureCapacity method can be called before insertion to increase the capacity of the ArrayList to improve the insertion efficiency. 
  Like LinkedList, ArrayList is also unsynchronized.

Vector 
  Vector is very similar to ArrayList, but Vector is synchronized. The Iterator created by Vector is the same interface as the Iterator created by ArrayList. However, 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), ConcurrentModificationException will be thrown when calling the Iterator method, so the exception must be caught.

The Stack class 
  Stack inherits from Vector and implements a last in first out stack. Stack provides 5 additional methods that allow Vector to be used as a stack. The basic push and pop methods, as well as the peek method to get the element at the top of the stack, the empty method to test whether the stack is empty, and the search method to detect the position of an element on the stack. After the Stack is created, it is an empty stack.

Set interface 
  Set is a collection that does not contain duplicate elements, that is, any two elements e1 and e2 have e1.equals (e2) = false, and Set has at most one null element. 
  Obviously, the constructor of Set has a constraint, and the incoming Collection parameter cannot contain duplicate elements. 
  Please note: Must be careful to handle mutable objects (Mutable Object). If the variable elements in a Set change their state, leading to Object.equals (Object) = true will cause some problems.

Map interface 
  Please note that Map does not inherit the Collection interface, Map provides key to value mapping. A map cannot contain the same key, and each key can only map one value. The Map interface provides three sets of views. The contents of the Map can be regarded as a set of keys, a set of values, or a set of key-value mappings.

Hashtable class 
  Hashtable inherits the Map interface and implements a key-value mapped hash table. Any non-null object can be used as a key or value. 
  Add data using put (key, value), and get data using get (key), the time cost 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, 3 into Hashtable, their keys are "one", "two", "three": 
    Hashtable numbers = new Hashtable (); 
    numbers.put ("one" , new Integer (1)); 
    numbers.put ("two", new Integer (2)); 
    numbers.put ("three", new Integer (3)); 
  To take out 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 position 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 hashCodes must be the same, but if the two objects are different, their hashCodes are not necessarily different. If the hashCodes of the two different objects are the same, this phenomenon is called a conflict. Conflicts will increase the time overhead of operating the hash table. So try to define a good hashCode () method, which can speed up the operation of the hash table. 
  If the same object has different hashCode, the operation of the hash table will produce unexpected results (the expected get method returns null). To avoid this problem, only one thing needs to be kept in mind: to repeat the equals method and hashCode method at the same time, Do n’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 you consider HashMap as a Collection (values ​​() method can return Collection), its iteration sub-operation time cost 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 is too low.

WeakHashMap class 
  WeakHashMap is an improved HashMap. It implements a "weak reference" to a key. If a key is no longer referenced externally, the key can be recovered by the GC.

Summary 
  If it involves stack, queue and other operations, you should consider using List. For fast 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 in one thread, consider the asynchronous class, which is more efficient. If multiple threads may operate on a class at the same time, the synchronized class should be used. 
  Pay special attention to the operation of the hash table, as the object of the key must correctly replicate the equals and hashCode methods. 
  Try to return the interface instead of the actual type, such as returning List instead of ArrayList, so that if you need to replace ArrayList with LinkedList in the future, the client code does not need to be changed. This is for abstract programming.

Java collection class map set list arraylist hashmap hashtable (turn)

The methods of Vector are all synchronized (Synchronized), which is thread-safe (Thread-safe), and the method of ArrayList is not, because the synchronization of threads must affect performance, therefore, the performance of ArrayList is better than Vector. 
When the elements in Vector or ArrayList exceed its initial size, Vector will double its capacity, and ArrayList only increases the size of 50%, so that ArrayList is conducive to saving memory space. The performance of
Hashtable and HashMap   
are similar to Vector and ArrayList. For example, the methods of Hashtable are synchronous, but those of HashMap are not. 
ArrayList and LinkedList   
For processing a list of data items, Java provides two classes ArrayList and LinkedList. The internal implementation of ArrayList is based on the internal array Object [], so conceptually, it is more like an array, but the internal implementation of LinkedList is based on a Group connected records, so, it is more like a linked list structure, so, they are very different in performance.   
(1) From the above analysis, we can see that when inserting data in front of or in the middle of ArrayList, you must move all the data behind it accordingly, which will inevitably take more time, so when your operation is in a column of data When you add data behind rather than in front or in the middle, and you need to randomly access the elements, using ArrayList will provide better performance.   
(2) When accessing an element in the linked list, you must search for it one element at a time from the end of the linked list along the connection direction until you find the desired element, so when your operation is in a column of data When adding or deleting data before or in the middle, and accessing the elements in sequence, you should use LinkedList.   
(3) If in the programming, the two situations of 1, 2 appear alternately, at this time, you can consider using a generic interface such as List, without having to care about the specific implementation. In specific situations, its performance is determined by the specific implementation. To guarantee. 
Set the initial size of the collection class. The size 
of most classes in the Java collection framework can increase with the number of elements. We do n’t seem to care about its initial size, but if we consider the performance of the class , You must consider setting the initial size of the collection object as much as possible, which will greatly improve the performance of the code. For example, the default initial size of Hashtable is 101, and the loading factor is 0.75, that is, if the number of elements in it exceeds 75 It must increase the size and reorganize the elements, so if you know that the exact number of elements is 110 when creating a new Hashtable object, then you should set its initial size to 110 / 0.75 = 148 In this way, you can avoid reorganizing memory and increasing the size. 
Especially to understand: 
Hashtable class 
  Hashtable inherits the Map interface and implements a key-value mapped hash table. Any non-null object can be used as a key or value. 
  Add data using put (key, value), and get data using get (key), the time cost 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, 3 into Hashtable, their keys are "one", "two", "three": 
    Hashtable numbers = new Hashtable (); 
    numbers.put (“one”, new Integer (1)); 
    numbers.put (“two”, new Integer (2)); 
    numbers.put (“three”, new Integer (3 )); 
  To take out a number, such as 2, use the corresponding key: 
    Integer n = (Integer) numbers.get ("two"); 
    System.out.println ("two =" + n); 
   due to the object as the key The position of the corresponding value will be determined by calculating its hash function, so any object that is a 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 hashCodes must be the same, but if the two objects are different, their hashCodes are not necessarily different. If the hashCodes of the two different objects are the same, this phenomenon is called a conflict. Conflicts will increase the time overhead of operating the hash table. So try to define a good hashCode () method, which can speed up the operation of the hash table. 
  If the same object has different hashCode, the operation of the hash table will produce unexpected results (the expected get method returns null). To avoid this problem, only one thing needs to be kept in mind: to repeat the equals method and hashCode method at the same time, Do n’t just write one of them. 
  Hashtable is synchronized. 
HashMap class 
   HashMap is similar to Hashtable, except that HashMap is asynchronous and allows null, that is, null value and null key. , But when you consider HashMap as a Collection (values ​​() method can return Collection), its iteration sub-operation time cost 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 is too low. 
The LinkedList class 
   LinkedList implements the List interface, allowing null elements. In addition, LinkedList provides additional get, remove, and insert methods at the beginning or end of the LinkedList. These operations make LinkedList can be used as a stack (stack), queue (queue) or two-way queue (deque). 
  Note that LinkedList has no synchronization method. If multiple threads access a List at the same time, you must implement access synchronization yourself. One solution is to construct a synchronized List when creating the List: 
    List list = Collections.synchronizedList (new LinkedList (...)); 
ArrayList class 
  ArrayList implements a variable-sized array. It allows all elements, including null. ArrayList is not synchronized. 
The running time of size, isEmpty, get, and set methods is constant. However, the cost of the add method is an amortized constant, and adding n elements takes O (n) time. The running time of other methods is linear. 
   Each ArrayList instance has a capacity, which is the size of the array used to store the elements. This capacity can automatically increase as new elements are added, but the growth algorithm is not defined. When a large number of elements need to be inserted, the ensureCapacity method can be called before insertion to increase the capacity of the ArrayList to improve the insertion efficiency. 
  Like LinkedList, ArrayList is also unsynchronized. 
Vector 
   Vector is very similar to ArrayList, but Vector is synchronized. The Iterator created by Vector is the same interface as the Iterator created by ArrayList. However, 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), ConcurrentModificationException will be thrown when calling the Iterator method, so the exception must be caught.

Guess you like

Origin www.cnblogs.com/kelelipeng/p/12722072.html