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

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);

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;
}
}

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));
}

2: Using an iterator (Iterator ):

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

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!

Statement
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
Top 4 JavaScript Frameworks in 2025: React, Angular, Vue, SvelteTop 4 JavaScript Frameworks in 2025: React, Angular, Vue, SvelteMar 07, 2025 pm 06:09 PM

This article analyzes the top four JavaScript frameworks (React, Angular, Vue, Svelte) in 2025, comparing their performance, scalability, and future prospects. While all remain dominant due to strong communities and ecosystems, their relative popul

Spring Boot SnakeYAML 2.0 CVE-2022-1471 Issue FixedSpring Boot SnakeYAML 2.0 CVE-2022-1471 Issue FixedMar 07, 2025 pm 05:52 PM

This article addresses the CVE-2022-1471 vulnerability in SnakeYAML, a critical flaw allowing remote code execution. It details how upgrading Spring Boot applications to SnakeYAML 1.33 or later mitigates this risk, emphasizing that dependency updat

Node.js 20: Key Performance Boosts and New FeaturesNode.js 20: Key Performance Boosts and New FeaturesMar 07, 2025 pm 06:12 PM

Node.js 20 significantly enhances performance via V8 engine improvements, notably faster garbage collection and I/O. New features include better WebAssembly support and refined debugging tools, boosting developer productivity and application speed.

How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?Mar 17, 2025 pm 05:44 PM

The article discusses implementing multi-level caching in Java using Caffeine and Guava Cache to enhance application performance. It covers setup, integration, and performance benefits, along with configuration and eviction policy management best pra

How does Java's classloading mechanism work, including different classloaders and their delegation models?How does Java's classloading mechanism work, including different classloaders and their delegation models?Mar 17, 2025 pm 05:35 PM

Java's classloading involves loading, linking, and initializing classes using a hierarchical system with Bootstrap, Extension, and Application classloaders. The parent delegation model ensures core classes are loaded first, affecting custom class loa

How to Share Data Between Steps in CucumberHow to Share Data Between Steps in CucumberMar 07, 2025 pm 05:55 PM

This article explores methods for sharing data between Cucumber steps, comparing scenario context, global variables, argument passing, and data structures. It emphasizes best practices for maintainability, including concise context use, descriptive

How can I implement functional programming techniques in Java?How can I implement functional programming techniques in Java?Mar 11, 2025 pm 05:51 PM

This article explores integrating functional programming into Java using lambda expressions, Streams API, method references, and Optional. It highlights benefits like improved code readability and maintainability through conciseness and immutability

Iceberg: The Future of Data Lake TablesIceberg: The Future of Data Lake TablesMar 07, 2025 pm 06:31 PM

Iceberg, an open table format for large analytical datasets, improves data lake performance and scalability. It addresses limitations of Parquet/ORC through internal metadata management, enabling efficient schema evolution, time travel, concurrent w

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.