Differences between set, list, and map

Source: Internet
Author: User
Differences between set, list, and map Java collections are mainly divided into three types:
  • Set)
  • List)
  • Map)
To thoroughly understand a set, first understand the arrays we are familiar with: arrays are fixed in size, and the same array can only store data of the same type (basic type/reference type ), the Java set can store a group of data with an unfixed number of operations. All Java collections are located in the Java. util package! Java collections can only store reference data types, but cannot store basic data types. Differences between the next set and array: (reference: Thinking in algorithm 03. array of data structures)
  1. <Span style = "font-family: Microsoft yahei; font-size: 12px;"> there are no collections in the world (only arrays refer to the C language), but some people want them, so they have a collection.
  2. Some people want an array that can be automatically expanded, so the list
  3. Some people want to see if there are repeated arrays, so they have set
  4. Some people want to have the number of automatically sorted groups, so they have treeset, treelist, and tree **
  5. Almost some collections are implemented based on arrays.
  6. Because a set encapsulates arrays, arrays are always faster than any other set.
  7. However, any set provides more functions than arrays.
  8. 1. the array declares the type of the elements it holds, but the set does not. This is because the collection stores their elements in the form of objects.
  9. 2. An array instance has a fixed size and cannot be scaled. The set size can be dynamically changed as needed.
  10. 3. An array is a readable/writable Data Structure-there is no way to create a read-only array. However, you can use the readonly method provided by the set to use the set in read-only mode. This method returns the read-only version of a set.

Array is the most efficient method for Java's "Storage and random access to a series of objects. 

1,
High efficiency, but the capacity is fixed and cannot be changed dynamically.
Another disadvantage of array is that,The actual number of elements in the array cannot be determined. length only tells us the size of the array..

 

2. There isArrays class, used to operate the Array.
Arrays has a set of static functions,
Equals (): checks whether two arrays are equal. Array has the same number of elements, and all corresponding elements are equal to each other.
Fill (): Enter the value in array.
Sort (): used to sort arrays.
Binarysearch (): Search for elements in the sorted array.
System. arraycopy (): copying an array.

If you do not know how many objects are needed when writing a program and need to automatically expand the capacity when the space is insufficient, you need to use the container class library. array is not applicable. So we need to use a set. Let's start to discuss Java collections. Collection type: Collection: List, Set
Map: hashmap, hashtable1.1 collection Interface collection is the most basic set interface and declares a general method applicable to Java collections (including only set and list. Both set and list inherit from conllection and map.

 

1.1.1 methods of the collection interface:
  1. Boolean add (Object O): Add an object reference to the set
  2. Void clear (): deletes all objects in the set, that is, they no longer hold references to these objects.
  3. Boolean isempty (): determines whether the set is empty.
  4. Boolean contains (Object O): determines whether a specified object is referenced in a collection.
  5. Iterator (): returns an iterator object that can be used to traverse elements in the set.
  6. Boolean remove (Object O): deletes an object reference from the set.
  7. Int size (): returns the number of elements in the set.
  8. Object [] toarray (): returns an array containing all elements in the set.

 

The iterator () and toarray () methods are used for all elements of the set. The former returns an iterator object, and the latter returns an array containing all elements in the set. 1.1.2 The iterator interface declares the following methods:
  1. Hasnext (): determines whether the elements in the set have been traversed. If not, true is returned.
  2. Next (): returns the next element.
  3. Remove (): deletes an element returned by the next () method from the set.

1.2 set is the simplest set. Objects in the set are not sorted in a specific way, and No repeated objects. The Set interface mainly implements two implementation classes:
  • Hashset: The hashset class uses a hash algorithm to access objects in a set. The access speed is relatively high.
  • Treeset: The treeset class implements the sortedset interface to perform operations on objects in the set.Sort.
Set usage: stores object references without repeated objects
  1. 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 the add () method of set determine whether the object has been stored in the collection?

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

      

Functions and methods of Set

Set has the same interface as collection, so there is no additional function, unlike the previous two different lists. In fact, set is a collection, but the behavior is different. (This is a typical application of inheritance and Polymorphism: different behavior .) Set does not store repeated elements (it is more responsible for determining how to determine if the elements are the same)

Set: Each element stored in the set must be unique because the set does not store duplicate elements. The equals () method must be defined for the element added to the set to ensure the uniqueness of the object. Set has the same interface as collection. The Set interface does not guarantee the order of maintenance elements.

 

  • Hashset: A set designed for quick search. The object stored in the hashset must define hashcode ().
  • Treeset: The set that stores the order. The bottom layer is the tree structure. It can be used to extract ordered sequences from the set.
Linkedhashset: query speed with a hashset, and internal use of the linked list to maintain the order of elements (insert order ). When you use the iterator to traverse the set, the result is displayed in the order of element insertion.

 

1.3 The feature of a list is that its elements are stored linearly, Set to store duplicate objects.

The main implementation classes of the List interface include: (see the difference between arraylist and list)
  • Arraylist (): indicates that the length of an array can be changed. Random Access to elements is allowed, and it is slow to insert or delete elements to arraylist.
  • Linked List (): uses the Linked List Data Structure in implementation. Fast insertion and deletion, and slow access.
For random access to a list, only random elements are retrieved at a specific location. The get (INT index) method of list puts back the object at the index location specified by the index parameter in the set. The subscript starts from "0. The two most basic methods to retrieve all objects in a set:


1: For Loop and get () method:

 

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

      

 

2: Use iterator ):

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

      

Functions and methods of list


There are actually two types of list: one is the basic arraylist, which has the advantage of random access elements and the other is the more powerful random list, which is not designed for fast random access, instead, it has a set of more general 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 the collection so that you can insert and remove elements to the list (this is only recommended for using the list .) A list can generate listiterator, which can be used to traverse the list in two directions, or to insert and remove elements from the list.
  • Arraylist: List implemented by arrays. Quick and Random Access to elements is allowed, but it is slow to insert and remove elements into the list. Listiterator should only be used to traverse the arraylist from the forward, rather than to insert and remove elements. This is much higher than the overhead of the shortlist.
  • Optimize list: the sequential access is optimized, and the overhead of insert and delete to the list is not large. Random Access is relatively slow. (Use arraylist instead .) The methods include addfirst (), addlast (), getfirst (), getlast (), removefirst (), and removelast (), these methods (not defined in any interface or base class) allow the consumer list to be used as a stack, queue, and bidirectional queue.

 

1.4 Map)

Map is a set 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 set, as long as the key object is given, the corresponding value object is returned.

Common map methods:

1. add and delete operations:

 

  1. Object put (Object key, object Value): Add an element to the set
  2. Object remove (Object key): deletes key-related elements.
  3. Void putall (map t): Adds all elements from a specific image to the image.
  4. Void clear (): deletes all mappings from the image.

 

2 query operations:

Object get (Object key): obtains the value related to the keyword key. Duplicate key objects are not allowed in the map set. That is to say, the comparison results of any two key objects through the equals () method are false ., however, you can map any number of keys to the same value object.

 

Functional methods of Map

The put (Object key, object Value) method adds a "value" (desired) and a "key" (key) associated with the "value" (use it for search ). The get (Object key) method 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, and identityhashmap. They all have the same basic interface map, but the behavior, efficiency, sorting policy, saving object lifecycle and determining "key" equivalent policies are different.

Execution efficiency is a big problem of map. Let's look at what get () is going to do, and we will understand why searching for "keys" in arraylist is quite slow. This is where hashmap improves speed. Hashmap uses a special value called hash code to replace the slow key-to-key search. The hash code is a "relatively unique" used to represent the int value of an object. 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 an object for quick query. This method can significantly improve the performance.

Map: Maintain the correlation between "key-value pairs" so that you can use "key" to find "value"

Hashmap: Implementation of map based on hash. The overhead of inserting and querying "key-value pairs" is fixed. You can use the constructor to set the Capacity and load factor to adjust the container performance.

Linkedhashmap: similar to hashmap, but when traversing it iteratively, the order in which "key-value pairs" are obtained is the insertion order, or the least recently used (LRU) Order. It is only a little slower than hashmap. It is faster during iterative access because it uses the linked list to maintain the internal order.

Treemap: based on the data structure of the red and black trees. When you view "keys" or "key-value pairs", they are sorted (the order is determined by comparabel or comparator ). Treemap features that the results you get are sorted. Treemap is the only map with submap () method. It can return a subtree.

Weakhashmao: weak Key Map. objects used in map are also allowed to be released. This is designed to solve special problems. If a reference other than map points to a key, the key can be recycled by the garbage collector.

Identifyhashmap: Use = to replace the hash map used by equals () to compare the "key. Designed to solve special problems.

 

1.4 differences 1.4.1 differences between collection and map

The number of elements stored in each container is different.
Collection type, each location has only one element.
Map type, holding key-value pair, like a small database.

1.4.2 subcategory relationship

Collection
-- List: stores elements in a specific order. Therefore, the order obtained may be different from the order placed.
-- Arraylist/vector list/vector
-- Set: duplicate elements cannot be contained.
-- Hashset/treeset
Map
-- Hashmap
-- Hashtable
-- Treemap

1.4.3. Other features

List, set, and map are regarded as object types.

Collection, list, set, and map are all interfaces and cannot be instantiated.
The arraylist, vector, hashtable, and hashmap inherited from them are concrete classes, which can be instantiated.
The vector container knows exactly the type of the object it holds. Vector does not perform boundary check.

Conclusion 1. If operations such as stacks and queues are involved, you should consider using the list. For elements that need to be inserted and deleted quickly, you should use the random list. If you need to quickly access elements randomly, you should use the arraylist.
2. if the program is in a single-threaded environment or the access is only performed in one thread, the efficiency of non-synchronous classes is high. If multiple threads may operate on one class at the same time, synchronous classes should be used.
3. In addition to using treeset and treemap for sorting, hashset and hashmap should be used because they are more efficient.
4. Pay special attention to the operations on the hash table. The equals and hashcode methods should be correctly rewritten as the key object.
 
5. The Container class can only hold the object reference (pointer to the object), instead of copying the object information to a certain position in the series. Once an object is placed in a container, the type information of the object is lost.
6. Try to return the interface rather than the actual type. For example, if the list is returned rather than the arraylist, the client code does not need to be changed if you need to replace arraylist with the explain list later. This is for abstract programming.

 

Note: 1. collection does not have the get () method to retrieve an element. You can only use iterator () to traverse elements. 2. Set and collection have the same interface. 3. list. You can use the get () method to retrieve an element at a time. Use numbers to select one of a bunch of objects, get (0 ).... (Add/get) 4. arraylist is generally used. Use the queue list to construct the stack and queue. 5. Map uses put (K, v)/get (K) and containskey ()/containsvalue () to check whether a key/value exists. Hashmap uses the hashcode of the object to quickly find the key. 6. Elements in map can be extracted separately from the key sequence and value sequence. Use keyset () to extract the key sequence and generate a set for all the keys in the map. Use values () to extract the value sequence and generate a collection for all values in the map. Why does one generate a set and one generate a collection? That's because the key is always unique and the value can be repeated.

Differences between set, list, and map

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.