Java Serial 149-Collection Class Section

Time:2022-9-21

1. The difference between Collections and Collections

  • Collection is an interface class that is the parent interface of Set and List interfaces
  • Collections is a tool class that should not be initialized as an object. It contains many static methods for collection operations.

Second, the difference between Set and List

  • Both Set and List are interfaces, but they are different
  • Set is an unordered collection. The elements placed in it cannot be repeated and can be used for deduplication.
  • List is an ordered collection, in accordance with the principle of first in first put

3. The difference between ArrayList\LinkedList\Vector

  • The bottom layer of ArrayList is an array; its initial capacity is very small, if no capacity is specified, it will automatically expand to 1.5 times the original size; if we need a lot of space, we can manually give it an initial capacity; it contains get( ) and set() methods are used to retrieve elements, etc.; this is a thread-unsafe List
  • The bottom layer of Vector is also an array; its initial capacity is very small. If no capacity is specified, it will automatically expand to twice the original size; if we need a lot of space, we can manually give it an initial capacity; this is thread-safe List of
  • The bottom layer of LinkedList is atwo-wayLinked list, so it has better performance when adding or deleting elements; this is also a thread-unsafe List.

Note: ArrayList is internally optimized with transient. In the writeObject() method of the internal code, only non-null elements are stored, while Vector stores all elements. Therefore, when the content is the same, Vector occupies The space is larger than that of ArrayList; in a sense, ArrayList is an optimized storage method under the current thread, and Vector uses synchronized for synchronization to ensure thread safety.

4. An expansion code

int oldCapacity = 5;int newCapacity = oldCapacity + (oldCapacity <

Five, the difference between SynchronizedList and Vector

  • Let's talk about how to use it first;

    • In the case of multi-threading, you can directly use Vector to construct a thread-safe List for use
    • SynchronizedList is an inner class of Collections, we can use it like this
List list1 = new ArrayList();SynchronizedList list = Collections.synchronizedList(list1);
  • The difference between the two is that Vector is in the form of a synchronized method, and SynchronizedList is in the form of a block of synchronized code.

6. Source code: