List,set and map in Java and their differences

Source: Internet
Author: User
Tags joins

The collections in Java consist of three classes, set, list, and map, all in the Java.util package, and set, list, and map are interfaces that have their own implementation classes. The implementation class of set mainly has the HashSet and Treeset,list implementation class mainly has the Arraylist,map implementation class mainly has HashMap and treemap.

Collection is the most basic set interface that declares a common method for Java collections, and both list and set inherit from the collection interface.

Method of Collection interface

Boolean Add (Object O): Adds a reference to an object to the collection

void Clear (): Deletes all objects in the collection, i.e. no longer holds references to those objects

Boolean IsEmpty (): Determines whether the collection is empty

Boolean contains (object O): Determines whether a reference to a particular object is held in the collection

Iterartor iterator (): Returns a Iterator object that can be used to iterate through the elements in the 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 that includes all the elements in the collection

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

Collection does not have a get () method to get an element. Elements can only be traversed by iterator ().

The iterator interface declares the following methods

Hasnext (): Determines whether the elements in the collection are traversed, and if not, returns true

Next (): Returns the next element

Remove (): Removes the last element returned from the collection with the next () method.

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

The Hashset:hashset class accesses the objects in the collection according to the hashing algorithm, and the access speed is relatively fast.

The Treeset:treeset class implements the SortedSet interface and is able to sort the objects in the collection.

function method of List

There are actually two kinds of lists: One is the basic ArrayList, the advantage is the random access element, the other is the more powerful linkedlist, it is not for the fast random access design, but has a more general method.

List: Order is the most important feature of the list: it ensures that the elements are maintained in a specific order. The list adds a number of methods to collection, allowing you to insert and remove elements to the middle of the list (this is recommended for linkedlist use only. A list can generate Listiterator, which can be used to traverse a list in two directions or to insert and remove elements from the middle of a list.

ArrayList: A list implemented by an array. Allows fast random access to elements, but inserts and removes elements in the middle of the list is slow. Listiterator should only be used to traverse the ArrayList backward, not to insert and remove elements. Because that's much more expensive than linkedlist.

LinkedList: Sequential access is optimized, and the cost of inserting and deleting to the list is small. Random access is relatively slow. (use ArrayList instead.) ) also has the following methods: AddFirst (), AddLast (), GetFirst (), GetLast (), Removefirst (), and Removelast (), which are not defined in any interface or base class Enables LinkedList to be used as stacks, queues, and bidirectional queues.

function method of Set

The set has exactly the same interface as the collection, so there is no additional functionality. In fact set is collection, but behaves differently. This is a typical application of inheritance and polymorphic thinking: behave differently. Set does not save duplicate elements (more responsible for how the elements are judged)

Set: Each element that is stored in the set must be unique because set does not save duplicate elements. The element that joins the set must define the Equals () method to ensure the uniqueness of the object. The set has exactly the same interface as the collection. The set interface does not guarantee the order in which elements are maintained.

HashSet: Set for quick find design. The object that is deposited into the hashset must define HASHCODE ().

TreeSet: The set of the save order, the underlying tree structure. Use it to extract ordered sequences from the set.

Linkedhashset: has hashset query speed, and internally uses the chain list to maintain the order of elements (the Order of insertions). The result is displayed in the order in which the elements are inserted when iterating through the set using Iterators.

function method of Map

Method put (Object key, object value) adds a "value" (What you Want) and the "Key" (key) associated with the value (using it to find). Method get (Object key) returns the value associated with the given "key". You can test whether a "key" or "value" is included in the map with ContainsKey () and Containsvalue (). The standard Java class library contains several different map:hashmap, TreeMap, Linkedhashmap, Weakhashmap, and Identityhashmap. They all have the same basic interface map, but the behavior, the efficiency, the sorting strategy, the life cycle of the saved object, and the policy that determines the "key" equivalence are different.

Execution efficiency is a big problem in map. Look at what get () does, and you'll see why searching for "keys" in ArrayList is pretty slow. And that's where the hashmap to improve speed. HashMap uses a special value, called a hash code, to replace the slow search for keys. A hash code is a "relatively unique" int value that represents an object that is generated by converting some information of that object. All Java objects can produce hash codes, because Hashcode () is the method defined in the base class object.

HashMap is a quick query using the object's Hashcode (). This method can significantly improve performance.

MAP: Maintain the relevance of key-value pairs so that you can find "values" by "Keys"

Hashmap:map based on the implementation of the hash table. The cost 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 iterating through it, the order in which key-value pairs are obtained is their insertion order, or the least recently used (LRU) order. Just a little slower than HashMap. The iteration is accessed faster because it uses the list to maintain the internal order.

TREEMAP: Based on the implementation of red-black tree data structure. When you look at key or key-value pairs, they are sorted (the order is determined by comparabel or comparator). TreeMap is characterized by the fact that the results you get are sorted. TreeMap is the only map with the Submap () method, which can return a subtree.

Weakhashmap: The objects used in the weak key (weak key) Map,map are also allowed to be released: This is designed to solve special problems. If no references outside of map point to a key, the key can be reclaimed by the garbage collector.

Identifyhashmap:: Use = = instead of equals () to compare the "key" to the hash map. Designed to solve special problems.

List and set, map differences and applicable scenarios

1, List, set are inherited from the collection interface, map is not

2, List features: elements are placed in order, elements can be repeated, set features: elements are not placed in order, elements are not repeatable, repeating elements will be overwritten, (note: Although the element is not placed in the order, but the element in the set position is the element of the hashcode decision, its position is actually fixed, The object that joins the set must define the Equals () method, and the list supports the For loop, which is to iterate through the subscript, but the set can only be iterated, because he is unordered and cannot use subscript to get the desired value. )

3, set and list comparison:

Set: The retrieval element is inefficient, the deletion and insertion efficiency is high, and insertions and deletions do not cause the element position to change.

List: And arrays, lists can grow dynamically, find elements efficiently, and insert deleted elements inefficiently because they cause other elements to change position.

4, map suitable for storing key value pairs of data

5. Thread-Safe collection classes and non-thread-safe collection classes:

    • LinkedList, ArrayList, hashset are non-thread-safe, vector is thread-safe;
    • HashMap is non-thread-safe, Hashtable is thread-safe;
    • StringBuilder is non-thread-safe and StringBuffer is thread-safe.

The difference between ArrayList and LinkedList and the applicable scene

Arraylist:

Advantage: ArrayList is a data structure based on dynamic array, because the address is continuous, once the data is stored well, the query operation efficiency will be higher (in memory is attached).

Disadvantage: Because the address is continuous, ArrayList to move the data, so the insertion and deletion operation is less efficient.

LinkedList:

Advantages: LinkedList is based on the data structure of the linked list, the address is arbitrary, so in the open memory space when there is no need to wait for a continuous address, for new and delete operations Add and remove,linedlist more dominant. LinkedList for scenes that you want to work with or insert at a specified location

Disadvantage: Because the linkedlist to move the pointer, the query operation performance is relatively low.

Application Scenario Analysis:

When ArrayList is required for this access to the data, LinkedList is used when multiple additions to the data are needed to delete the modifications.

The difference between ArrayList and vector and the application scenario

ArrayList and vectors are all implemented using arrays, and there are three differences:

1, vector is multithreaded security, thread safety means that multithreading access to the same code, will not produce an indeterminate result. And ArrayList is not, this can be seen from the source code, the method of the vector class has synchronized to decorate, so that the vector in efficiency can not be compared with ArrayList;

2, two are used in linear continuous space storage elements, but when the space is not enough, the increase of the two classes are different.

3, vector can set the growth factor, and ArrayList not.

4, Vector is an old dynamic array, is thread synchronization, efficiency is very low, generally do not approve of the use.

Application Scenario Analysis:

1, vector is thread synchronization, so it is also thread-safe, and ArrayList is thread-asynchronous, is not secure. If the thread security factors are not taken into account, the ArrayList efficiency is generally higher.

2, if the number of elements in the collection is greater than the current collection of the length of the array, the use of data in the collection of large data, with a certain advantage of vector.

HashSet and TreeSet application scenarios

1, TreeSet is two difference tree (red black tree tree according to the structure), the data in the TreeSet is automatically sequenced, not allowed to put null values

2, HashSet is a hash table implementation, the data in the HashSet is unordered, can be put into null, but only a null, the values in both cannot be duplicated, such as the unique constraints in the database

3, HashSet required to put the object must implement the Hashcode () method, put the object, is the Hashcode code as the identity, and the same content of the string object, Hashcode is the same, so the content can not be duplicated. However, objects of the same class can be placed in different instances.

Application Scenario Analysis:

HashSet is based on the hash algorithm, and its performance is usually better than treeset. For a set that is designed for quick lookups, we should usually use hashset, and we use treeset when we need to sort the functions.

The difference between HashMap and TreeMap and Hashtable and the applicable scenes

HASHMAP: Non-thread safe

HASHMAP: Based on hash table implementation. The key classes you add with HashMap explicitly define hashcode () and Equals () [can override Hashcode () and Equals ()], and to optimize the use of hashmap space, you can tune the initial capacity and load factor.

TREEMAP: Non-thread-safe based on red-black tree implementation. TreeMap has no tuning option because the tree is always in equilibrium.

Application Scenario Analysis:

HashMap and Hashtable:hashmap removed the Hashtable contains method, but added the Containsvalue () and ContainsKey () methods. Hashtable synchronous, and HashMap is not synchronous, the efficiency is higher than Hashtable. HashMap allows null key values, while Hashtable is not allowed.

HashMap: Applies to inserting, deleting, and locating elements in map.

Treemap: For traversing keys (key) in natural order or in a custom order.

List,set and map in Java and their differences

Related Article

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.