The difference between Set, List and Map in Java

Reprinted from: http://jax-work-archive.blogspot.com/2015/02/java-setlistmap.html

Arrays have a fixed size, and the same array can only store data of the same type (basic type/reference type). Java collections can store and operate a set of data with a variable number. All Java collections are located in the java.util package! Java collections can only store reference type data, not basic data types.

Java collections are mainly divided into three types:

  • Set(set)
  • List(list)
  • Map


Collection interface:

Collection is the most basic collection interface and declares common methods applicable to Java collections (only Set and List). Both Set and List inherit Collection

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() Determine whether the collection is empty
  • boolean contains(Object o) Determine whether the collection holds a reference to a specific object
  • Iterartor iterator() Returns an Iterator object that can be used to iterate over the elements in the collection
  • boolean remove(Object o) Remove 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: Iterator() and toArray() methods are both used for all elements of 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() Removes the previous element returned by the next() method from the collection.


Set:

Set is the simplest kind of collection. The objects in the collection are not ordered in any particular way, and there are no duplicate objects.

The Set interface mainly implements two implementation classes:

  • HashSet The objects in the collection are accessed according to the hash algorithm, and the access speed is relatively fast.
  • TreeSet Implemented the SortedSet interface to sort objects in the collection.

Usage of Set: It stores references to objects, and there are no duplicate objects.

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()); //The number of objects in the print set is 2.  

How does Set's add() method determine whether an object is already 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:

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 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 A linked list data structure is used in implementation. Insertion and deletion are fast, access is slow.

For random access of List, only the elements at a specific position are retrieved randomly. 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 ways to retrieve 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: Use Iterator:

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


Map:

Map is a collection that maps key objects and value objects. Each element of Map 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:

  • Object put(Object key, Object value) Add elements to the collection
  • Object remove(Object key) Delete elements related to KEY
  • void putAll(Map t) Adds all elements from a specific image to that image
  • void clear() Remove all mappings from the image
  • 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() Returns the number of maps in the current image
  • boolean isEmpty() Determine if there are any mappings in the image
  • Object get(Object key) Get the value associated with the keyword key. The key objects in the Map collection are not allowed to be repeated. That is to say, the result of comparing any two key objects through the equals() method is false, but any multiple keys can be mapped exclusively to the same value object.


Collections collection utility class:

Collections provides static methods useful for Java collections.


Function methods of List

There are actually two kinds of List:
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
Ordering is the most important feature of List: it guarantees that a specific order of elements is maintained. List adds many methods to Collection, allowing elements to be inserted and removed from the List (this is only recommended for LinkedList). A List can generate a ListIterator, which can be used to traverse the List in both directions and to insert and remove elements from the middle of the List.
ArrayList
List implemented as an array. Allows fast random access to elements, but insertion and removal of elements from the middle of the List is slow. ListIterator should only be used to traverse an 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). It also has the following methods: addFirst(), addLast(), getFirst(), getLast(), removeFirst() and removeLast(). These methods (not defined in any interface or base class) allow LinkedList to be used as a stack, queue and deque.


Set function methods

Set has exactly the same interface as Collection, so it doesn't have any additional functionality, 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 that the elements are the same, it is more responsible)

Set: Each element stored in a Set must be unique because Sets do not store 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 lookup. Objects stored in a HashSet must define hashCode().
TreeSet
A Set that stores order, with a tree structure at the bottom. Use it to extract an ordered sequence from a Set.
LinkedHashSet
It has the query speed of HashSet, and internally uses a linked list 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.


Map function methods

The method put(Object key, Object value) adds a "value" (the thing you want) and the "key" associated with the "value" (use it to look up). Method get(Object key) Returns the "value" associated with the given "key". You can use containsKey() and containsValue() to test whether a Map contains a "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 saving objects, and strategies for determining "key" equivalence are different.

Execution efficiency is a big issue with Map. Looking 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 slow searches for keys. A "hash code" is a "relatively unique" int value used to represent an object, which is generated by converting some information about the object. All Java objects can generate hash codes because hashCode() is a method defined in the base class Object.

HashMap
Map is based on a hash table implementation. 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. HashMap uses the hashCode() of the object for quick query. This approach can significantly improve performance.
LinkedHashMap
Similar to HashMap, but when iterating through it, the order of obtaining "key-value pairs" is their insertion order, or 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 looking at "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 returns a subtree.
WeakHashMao
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 to a "key", then this "key" can be reclaimed by the garbage collector.
IdentifyHashMap
A hash map that uses == instead of equals() to compare "keys". Designed to solve special problems.


Summary:

The basic usage of Java collections has been summarized. The above are the most commonly used Java collections. For more details, please refer to the JDK help documentation. Haha, there are many applications of Map, specifically this one. Collections provides many List/Map practical methods, which are very useful for daily development.

List saves objects in the order they are entered, without sorting or editing. 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.

This siteOriginal articleAll follow "Attribution-NonCommercial-ShareAlike 4.0 License (CC BY-NC-SA 4.0)". Please keep the following tags for sharing and interpretation:

Original author:Jake Tao,source:"The difference between Set, List and Map in Java"

162
0 0 162

Further reading

Leave a Reply

Log inCan comment later
Share this page
Back to top