On the difference between set, list, and map in Java (1)

Source: Internet
Author: User
Tags set set

On the learning experience, the difference between set,list,map in Java, and the understanding of the Java collection is to think about arrays:

Arrays are fixed in size, and the same array can only hold data of the same type (base type/reference type), and Java Collections store and manipulate a set of data that is not fixed. All Java collections are located in the Java.util package! Java collections can only hold data of reference types and cannot hold basic data types.

There are three main types of Java collections:

    • Set (SET)

    • List (lists)

    • Map (map)

Collection interface: Collection is the most basic collection interface and declares a common method for Java collections (including set and list only). Both Set and list inherit the Conllection,map

Collection Interface Method:

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.

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.

Set usage: Holds reference to object, 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 ());//The number of objects in the Print collection is 2.

How does the Add () method of Set determine if an 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: The feature of a list is that its elements are stored in a linear fashion, and the collection can hold duplicate objects.

The main implementation classes of the list interface are:

    • ArrayList (): Represents the length can be changed by the group. Elements can be randomly accessed, and it is slow to insert and delete elements into ArrayList ().

    • LinkedList (): A linked list data structure is used in the implementation. Fast insertion and deletion, and slow access times.

For random access to a list, it is just random to retrieve the element at a particular location. The Get (int index) method of the List returns the object in the collection at the index location specified by the parameter index, starting with "0". The two most basic ways to retrieve all objects in a collection are:

1:for Loop and Get () method:

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

2: Using Iterators (Iterator):

    1. Iterator It=list.iterator ();

    2. while (It.hashnext) {

    3. System.out.println (It.next);

    4. }

Map (map):

Map is a collection of key object and value object mappings, each of which contains a pair of key objects and value objects. Map does not inherit from the collection interface when retrieving elements from the map collection, the corresponding value object is returned whenever the key object is given.

Common methods of Map:

1 Add, delete operation:

Object put (object key, Object value): Adding elements to the collection

Object remove (Object key): Delete the element associated with key

void Putall (Map t): Adds all elements from a specific image to the image

void Clear (): Remove all mappings from the image

2 Query operation:

Object get (Object key): Gets the value associated with the keyword key. The key object in the Map collection does not allow duplicates, which means that any two key objects that are compared by the Equals () method are false. But you can map any number of keys to the same value object.

Conllections: Collection Utility class. Conllections provides a static method that is useful for Java collections

Summarize:

Java collection of basic usage, are summed up, these are the usual most commonly used Java collection, specific other, but also to refer to the JDK Help document, hehe about the application of the MAP, there are many, specifically this, Conllections provides a lot of list/map practical method, Very useful for common development.

Boolean ContainsKey (Object key): Determine if there is a keyword key in the image

Boolean Containsvalue (Object value): Determines whether the value exists in the image

int size (): Returns the number of mappings in the current image

Boolean IsEmpty (): Determine if there are any mappings in the image

The list saves objects in the order in which they are entered, without sorting or editing operations. Set accepts only once for each object and uses its own internal ordering method (typically, you are only concerned about whether an element belongs to Set, not the order of it – otherwise you should use list). Map also saves one copy of each element, but this is based on the "key", and the map has a built-in sort, so it doesn't care about the order in which the elements are added. If the order of adding elements is important to you, you should use Linkedhashset or Linkedhashmap.

function method of List

There are actually two kinds of lis: 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, unlike the previous two different lists. In fact set is collection, but behaves differently. (This is a typical application of inheritance and polymorphic thinking: behavior that behaves 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.

Weakhashmao: 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.


This article is from "Ghost" blog, please make sure to keep this source http://caizi.blog.51cto.com/5234706/1561509

On the difference between set, list, and map in Java (1)

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.