Home > Java > javaTutorial > body text

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

高洛峰
Release: 2017-01-22 15:19:46
Original
1671 people have browsed it

Collection interface: Collection is the most basic collection interface, which declares common methods applicable to JAVA collections (including only Set and List). Both Set and List inherit Collection, the methods of Map

Collection interface:

boolean add(Object o): Add a reference to an object to the collection
void clear(): Delete All objects in the collection no longer hold references to these objects
boolean isEmpty(): Determine whether the collection is empty
boolean contains(Object o): Determine whether the collection holds references to specific objects
Iterartor iterator(): Returns an Iterator object, which can be used to traverse the elements in the collection
boolean remove(Object o): Removes a reference to an object from the collection

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

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

About: Iterator() and toArray() methods are both used for collections All elements in the 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(): Determine 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 kind of set. The objects in the collection are not ordered in a particular 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 set, and the access speed is relatively fast

TreeSet: The TreeSet class implements SortedSet Interface capable of sorting objects in a collection.

Usage of Set: It stores the reference of the object, there is no duplicate object

Set set=new HashSet();
String s1=new String("hello");
String s2=s1;
String s3=new String("world");
set.add(s1);
set.add(s2);
set.add(s3);
Copy after login

System.out.println(set.size());//Print set The number of objects in is 2.
How does the add() method of Set determine whether the object has been stored in the collection?

boolean isExists=false;
Iterator iterator=set.iterator();
while(it.hasNext()) {
String oldStr=it.next();
if(newStr.equals(oldStr)){
isExists=true;
}
}
Copy after login

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

The main implementation classes of the List interface include:
ArrayList(): represents an array whose length can be changed. Elements can be accessed randomly, and inserting and deleting elements into ArrayList() is slow.
LinkedList(): Use linked list data structure in implementation. Insertion and deletion are fast, access is slow.

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

1: for loop and get() method:

for(int i=0; i<list.size();i++){
System.out.println(list.get(i));
}
Copy after login

2: Using an iterator (Iterator ):

Iterator it=list.iterator();
while(it.hashNext){
System.out.println(it.next);
}
Copy after login

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

Common methods of Map:

1 Add and delete operations:

Object put(Object key, Object value): Add elements to the collection
Object remove( Object key): Remove elements related to KEY
void putAll(Map t): Add all elements from a specific image to the image
void clear(): Remove all mappings 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. In other words, the result of comparing any two key objects through the equals() method is false. However, any multiple keys can be mapped exclusively to the same value object.

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

Summary:

The basic usage of JAVA collections has been summarized. The above are the most commonly used JAVA collections. There are other specific ones. You have to refer to the JDK help documentation. Haha, there are many applications of Map, specifically this one. Collections provides many practical methods of List/Map, which are very useful for daily development.

boolean containsKey(Object key): Determine whether the keyword key exists in the image
boolean containsValue(Object value): Determine whether the value value exists in the image
int size(): Return to the current image Number of mappings
boolean isEmpty(): Determine whether there are any mappings in the image

List saves objects in the order in which they are entered, without sorting or editing operations. Set accepts each object only once and uses its own internal sorting method (usually, you only care about whether an element belongs to the Set, not its order - otherwise you should use a List).
Map also saves a copy of each element, but this is based on "key". Map also has built-in sorting, so it does not 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.

Function methods of List:
There are actually two types: one is the basic ArrayList, which has the advantage of randomly accessing elements. 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, making it possible to insert and remove elements from the middle of the List (this is only recommended for LinkedList.) A List can generate a ListIterator, which can be used to traverse the List in two directions, and can also be inserted and moved from the middle of the List. Remove elements.
ArrayList: List implemented by array. Allows fast random access to elements, but inserts and removes elements from the middle of the List very slowly. ListIterator should only be used to traverse the ArrayList from back to front, not to insert and remove elements. Because that is much more expensive than LinkedList.
LinkedList: Sequential access is optimized, and the overhead of inserting and deleting into the middle of the List is not large. Random access is relatively slow. (Use ArrayList instead.) Also has the following methods: addFirst(), addLast(), getFirst(), getLast(), removeFirst() and removeLast(), which (not defined in any interface or base class) make LinkedList can be used as a stack, queue and deque.

Functional methods of Set:
Set has exactly the same interface as Collection, so it does not have any additional functions, unlike the previous two different Lists. In fact, Set is Collection, but its behavior is different. (This is a typical application of inheritance and polymorphism: showing different behaviors.) Set does not save duplicate elements (as for how to judge the same elements, it is more responsible)

Set: Each element stored in Set is Must be unique because Set does not save duplicate elements. Elements added to the Set must define the equals() method to ensure the uniqueness of the object. Set and Collection have exactly the same interface. The Set interface does not guarantee that the order of elements is maintained.
HashSet: Set designed for quick search. Objects stored in HashSet must define hashCode().
TreeSet: Set to save the order, the bottom layer is a tree structure. Use it to extract an ordered sequence from a Set.

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

Function methods of Map:

Method put(Object key, Object value) adds a "value" (what you want) and the "key" associated with the "value" ) (use 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 the Map contains a certain "key" or "value".
The standard Java class library contains several different Maps: HashMap, TreeMap, LinkedHashMap, WeakHashMap, IdentityHashMap. They all have the same basic interface Map, but their behavior, efficiency, sorting strategy, life cycle of saved objects, and strategies for determining "key" equivalence are different.
Execution efficiency is a big problem for Map. If you look at what get() does, you'll understand why searching for a "key" in an ArrayList is quite slow. And this is where HashMap improves speed. HashMap uses special values, called hash codes, to replace the slow search for keys.
"Hash code" is a "relatively unique" int value used to represent an object. It is generated by converting certain information about 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 approach can significantly improve performance.

Map: Maintains the correlation of "key-value pairs" so that you can search for "value" by "key"

HashMap: Map is based on the implementation of hash table. The cost of inserting and querying key-value pairs is fixed. The capacity and load factor can be set through the constructor to adjust the performance of the container.
LinkedHashMap: Similar to HashMap, but when iterating through it, the order in which the "key-value pairs" are obtained is their insertion order, or the least recently used (LRU) order. Only slightly slower than HashMap. Iterative access is faster because it uses a linked list to maintain the internal order.
TreeMap: Implementation based on red-black tree data structure. When viewing "keys" 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 a 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 there is no reference outside the map pointing to a "key", this "key" can be recycled by the garbage collector.

IdentifyHashMap: A hash map that uses == instead of equals() to compare "keys". Designed to solve special problems.

For more related articles on the usage and differences of Set, List, and Map in Java, please pay attention to the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template