SoFunction
Updated on 2025-03-08

Introduction to the usage and differences between Set, List and Map in Java

Collection interface: Collection is the most basic collection interface, declaring common methods suitable for JAVA collections (including only Set and List). Set and List both inherit the Connection and Map

Methods of Collection interface:

boolean add(Object o): add a reference to an object to the collection
void clear(): Delete all objects in the collection, that is, no longer hold references to these objects
boolean isEmpty(): determines whether the set is empty
boolean contains(Object o): determines whether a reference to a specific object is held in the collection
Iterar iterator(): Returns an Iterator object that can be used to iterate over elements in a collection
boolean remove(Object o): removes a reference to an object from the collection

int size(): Returns the number of elements in the collection

Object[] toArray(): Returns an array containing all elements in the collection

About: The Iterator() and toArray() methods are used for all elements of a collection. The former returns an Iterator object, and the latter returns an array containing all elements in the collection.

The Iterator interface declares the following methods:

hasNext(): determines whether the elements in the collection have been traversed. If not, return true
next(): Return the next element
remove(): Remove the previous element returned by the next() method from the collection.

Set (set): Set is the simplest type of collection. Objects in the collection are not sorted in a specific way, and there are no duplicate objects. The Set interface mainly implements two implementation classes:

HashSet: The HashSet class uses the hash algorithm to access objects in the collection, and the access speed is relatively fast.

TreeSet: The TreeSet class implements the SortedSet interface, which can sort objects in the collection.

Usage of Set: It stores references to objects, no duplicate objects

Set set=new HashSet();
String s1=new String("hello");
String s2=s1;
String s3=new String("world");
(s1);
(s2);
(s3);

(());//The number of objects in the print collection is 2.
How does Set's add() method determine whether the object has been stored in the collection?

boolean isExists=false;
Iterator iterator=();
while(()) {
String oldStr=();
if((oldStr)){
isExists=true;
}
}

List: The characteristic of a List is that its elements are stored in a linear manner, and duplicate objects can be stored in the collection.

The main implementation classes of List interface include:
ArrayList(): represents that the length can be changed to an array. You can access elements randomly, and insert and delete elements into ArrayList() is slow.
LinkedList(): Uses a linked list data structure in the implementation. Fast insertion and deletion, slow access.

For the random access of List, it is to only randomly retrieve elements located at a specific location. The get(int index) method of List is put back into the object in the set at the index position specified by the parameter index, and the subscript starts from "0". The most basic two ways to retrieve all objects in a collection:

1: For loop and get() method:

for(int i=0; i<();i++){
((i));
}

2: Use iterator:

Iterator it=();
while(){
();
}


Map: Map is a collection of map key objects and value objects. Each element of it contains a pair of key objects and value objects.
Map does not inherit from the Collection interface When searching elements from the Map collection, as long as the key object is given, the corresponding value object will be returned.

Common methods for Map:

1 Add and delete operations:

Object put(Object key, Object value): Add elements to the collection
Object remove(Object key): Removes elements related to KEY
void putAll(Map t): Add all elements from a specific image to the image
void clear(): Remove all maps from the image

2 Query operation:

Object get(Object key): Get the value related to the keyword key. The key objects in the Map collection are not allowed to be repeated, that is, the result of any two key objects being compared by the equals() method is false. However, any multiple keys can be mapped exclusively to the same value object.

Connections: Collection utility class. Connections provides practical static methods for JAVA collections

Summarize:

The basic usage of JAVA collections has been summarized. The above are the most commonly used JAVA collections. For details, please refer to the JDK help document. Haha. There are many more applications of Map. This is specifically. Connections provides many practical methods for List /Map, which is very useful for daily development.

boolean containsKey(Object key): determines whether there is a keyword key in the image
boolean containsValue(Object value): determines whether there is a value in the image
int size(): Returns the number of maps in the current image
boolean isEmpty(): determines whether there is any mapping in the image

List saves objects in the order in which objects enter, without sorting or editing operations. Set accepts each object only once and uses its own internal sorting method (usually, you only care whether an element belongs to Set, not its order - otherwise you should use List).
Map also saves a copy of each element, but this is based on "key". Map also has built-in sorting, so it doesn't care about the order in which elements are added. If the order in which elements are added is important to you, you should use LinkedHashSet or LinkedHashMap.

List function method:
There are actually two types: one is the basic ArrayList, which has the advantage of random access to elements, and the other is the more powerful LinkedList, which is not designed for fast random access, but has a more general set of methods.

List: Order is the most important feature of List: it ensures that the specific order of elements is maintained. List adds many methods to Collection, allowing elements to be inserted and removed from the List (this is recommended for LinkedList.) A List can generate ListIterator, which can use it to traverse the List from both directions, or insert and remove elements from the List middle.
ArrayList: List implemented by array. Allows fast random access to elements, but inserting and removing elements into the middle of the List is slow. ListIterator should only be used to traverse the ArrayList from back to forward, rather than inserting and removing elements. Because that is much more expensive than LinkedList.
LinkedList: The sequential access is optimized, and the overhead of inserting and deleting into the middle of the List is not very high. Random access is relatively slow. (Use ArrayList instead.) Also has the following methods: addFirst(), addLast(), getFirst(), getLast(), removeFirst() and removeLast(). These methods (not defined in any interface or base class) make LinkedList use as a stack, queue, and bidirectional queue.

Set's function method:
Set has exactly the same interface as Collection, so there is no extra functionality, unlike two different Lists in front. In fact, Set is a Collection, but the behavior is different. (This is a typical application of inheritance and polymorphic thinking: performing different behaviors.) Set does not save duplicate elements (as for how to judge the elements are the same, it is more responsible)

Set: Each element stored in the Set must be unique because the Set does not save duplicate elements. The element added to the Set must define the equals() method to ensure the uniqueness of the object. Set has exactly the same interface as Collection. The Set interface does not guarantee the order of maintenance elements.
HashSet: Set designed for quick search. The object stored in the HashSet must define hashCode().
TreeSet: Set in the save order, the underlying layer is a tree structure. Use it to extract ordered sequences from Set.

LinkedHashSet: has the query speed of HashSet, and internally uses the linked list to maintain the order of elements (insertion order). So when you use an iterator to traverse Set, the results will be displayed in the order in which elements are inserted.

Map's function method:

Method put(Object key, Object value) adds a "value" (want something) and a "key" associated with "value" (using it to find). The method get(Object key) returns the "value" associated with the given "key". You can use containsKey() and containsValue() to test whether a "key" or "value" is included in the map.
The standard Java class library contains several different Map: HashMap, TreeMap, LinkedHashMap, WeakHashMap, IdentityHashMap. They all have the same basic interface map, but their behavior, efficiency, sorting strategies, saving the life cycle of objects, and determining the equivalent of "keys".
Execution efficiency is a big problem with Map. If you look at what get() wants to do, you will understand why searching for "key" in ArrayList is quite slow. And this is where HashMap speeds up. HashMap uses a special value called a hash code to replace slow searches for keys.
"Has code" is "relatively unique" to represent an object's int value, and it is generated by converting certain information of the object. All Java objects can generate hash codes because hashCode() is a method defined in the base class Object.
HashMap uses the hashCode() of the object for quick query. This method can significantly improve performance.

Map: Maintains the correlation of "key-value pairs" so that you can find "values" through "keys"

HashMap: Map is based on hash table implementation. The overhead of inserting and querying "key-value pairs" is fixed. The capacity capacity and load factor load factor can be set through the constructor to adjust the performance of the container.
LinkedHashMap: Similar to HashMap, but when iterates over it, the order in which the "key-value pair" is its insertion order, or the order of least recently used (LRU). Only a little slower than HashMap. It is faster to send when iterative access because it uses linked lists to maintain internal order.
TreeMap: Implementation based on red and black tree data structure. When you look at "key" or "key-value pairs", they are sorted (the order is determined by Comparabel or Comparator). The characteristic of TreeMap is that the results you get are sorted. TreeMap is the only Map with the subMap() method, which can return a subtree.
WeakHashMap: Weak key Map, objects used in the Map are also allowed to be released: This is designed to solve special problems. If no reference outside the map points to a "key", this "key" can be recycled by the garbage collector.

IdentifyHashMap: Use == instead of equals() to compare "keys". Designed specifically to solve special problems.