Set classes such as Map List Set in Java

Source: Internet
Author: User
Tags set set java util

Set classes such as Map List Set in Java

Map List Set and other collection classes:

I. Overview

In the JAVA util package, there are two sets of parent Interface Collection and Map. Their parent-child relationship:


+ Collection: extends: java. lang. Iterable
Vertex + List (the interface represents an ordered and reusable set. List)
│ ├ ArreyList (Class array, random access, no synchronization, thread safety)
│ Fully synchronized Vector (Class array synchronization thread)
│ Unsafe synchronized list (it is unsafe to insert or delete a Class linked list without synchronization threads)
│ Consumer Stack (Class)
Distinct + Set (the interface cannot contain repeated elements. Receive only once and perform internal sorting, set)
│ ├ HashSet (Class)
│ ├ LinkedHashSet (Class)
│ Define TreeSet (Class)

+ Map (Interface)
├ + Map (interface ing set)
│ ├ HashMap (the Class is not synchronized, And the thread is not secure. Except for differences and allowed null key values, it is roughly the same as Hashtable)
│ ├ Hashtable (Class synchronization, thread security. The null key value cannot be implemented)
│ Combine + SortedMap Interface
│ ├ TreeMap (Class)
│ ├ WeakHashMap (Class)

The following is a simple description of many interfaces and classes: first, let's not go over arrays)

1. High efficiency, but the capacity is fixed and cannot be changed dynamically. Another disadvantage of array is that it cannot determine the actual number of elements in the array. length only tells us the array capacity.
2. There is an Arrays class in Java that is used to operate Arrays.
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.

I. Differences between Array and set:
1) arrays are fixed in size, and the same array can only store data of the same type (basic type/reference type)
2) a java set can store a set of data with an unfixed number of operations.
3) if the program does not know how many objects are needed and the capacity needs to be automatically expanded when the space is insufficient, the container class library is required. array is not applicable. The difference between two set map lists is that they are set interfaces.

Set -- the values in the set cannot be duplicated, and the data structure is unordered.
List -- the values in the list can be repeated because it is an ordered data structure.
Map-paired data structure. The key value must be unique (the key cannot be the same; otherwise, the value must be replaced)

List stores objects in the order they enter, without sorting or editing.

Set accepts each object only once and uses its own internal sorting method (generally, you only care about whether an element belongs to the Set but not its order-otherwise, you should use the List ).

Map also saves a copy of each element, but this is based on the "key". Map also has built-in sorting, so it does not care about the order of element addition. If the order of adding elements is important to you, you should use LinkedHashSet or LinkedHashMap.

Collection is a Collection of objects. Collection has two subinterfaces: List and Set.

List can be obtained through subscript (1, 2 ..), the value can be repeated


The Set value can only be Set through the cursor, and the value cannot be repeated.


ArrayList, Vector, and aggregate List are implementation classes of List.
ArrayList is thread-insecure, and Vector is thread-safe. The underlying layers of these two classes are implemented by arrays.
The producer list is thread unsafe, and the underlying layer is implemented by the linked list.


Map is a set of key-value pairs.
HashTable and HashMap are Map implementation classes.
HashTable is thread-safe and cannot store null values.
HashMap is NOT thread-safe and can store null values.

Iii. Collections class and Collection Interface

Collections is a help class for collection classes. It provides a series of static methods for searching, sorting, thread security, and other operations on various sets.

Collection is the most basic Collection interface. A Collection represents a group of objects, namely, Elements of the Collection ). Some collections allow the same elements while others do not. Some can be sorted, while others cannot. The Java SDK does not provide classes that directly inherit from collections. The classes provided by the Java SDK are the "subinterfaces" that inherit from collections, such as List and Set.

All classes that implement the Collection interface must provide two standard constructor: A non-parameter constructor is used to create an empty Collection, A constructor with the Collection parameter is used to create a new Collection, which has the same elements as the imported Collection. The next constructor allows you to copy a Collection.

Traversal of a Collection class: traversing a common Collection:

How to traverse every element in the Collection? Regardless of the actual type of Collection, it supports an iterator () method. This method returns an iterator, and each element in the Collection can be accessed one by one using this iterator. The typical usage is as follows:

 

  1. Iterator it = collection. iterator (); // obtain an Iterator
  2. While (it. hasNext ()){
  3. Object obj = it. next (); // obtain the next element.
  4. }

    The two interfaces derived from the Collection interface are List and Set. List stores objects in the order they enter, without sorting or editing. Set accepts each object only once and uses its own internal sorting method (generally, you only care about whether an element belongs to the Set but not its order-otherwise, you should use the List ).

    4. List interface. An ordered and repeatable set actually has two types of List: one is the basic ArrayList, which has the advantage of random access elements and the other is the more powerful List, it is not designed for fast random access, but a more general method.

    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 elements can be inserted and removed from 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.

    1. ArrayList class

    1) ArrayList implements an array of variable sizes. It allows all elements, including null. ArrayList is not synchronized.
    2) the running time of the size, isEmpty, get, and set methods is constant. However, the overhead of the add method is the constant of the allocation. It takes O (n) to add n elements. The running time of other methods is linear.
    3) Each ArrayList instance has a Capacity, that is, the size of the array used to store elements. This capacity can automatically increase with the addition of new elements, but the growth algorithm is not defined. When a large number of elements need to be inserted, you can call the ensureCapacity method before insertion to increase the ArrayList capacity to improve the insertion efficiency.
    4) Like the synchronized list, ArrayList is also non-synchronous (unsynchronized ).

    5) 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.
    2. Vector class
    The Vector is very similar to the ArrayList, but the Vector is synchronized. Although the Iterator created by Vector is the same interface as the Iterator created by ArrayList, because Vector is synchronous, when an Iterator is created and in use, another thread changes the state of the Vector (for example, adding or deleting some elements). When calling the Iterator method, ConcurrentModificationException is thrown. Therefore, this exception must be caught.

    3. Sort list class
    The listlist interface allows null elements. In addition, the values list provides additional get, remove, and insert methods at the beginning or end of the values list. For example, addFirst (), addLast (), getFirst (), getLast (), removeFirst (), and removeLast (), these methods (not defined in any interface or base class ). These operations enable the queue list to be used as a stack, queue, or two-way queue (deque ).
    Note that the synchronized list method is not available. If multiple threads access a List at the same time, they must implement access synchronization by themselves. One solution is to construct a synchronized List when creating a List:
    List list = Collections. synchronizedList (new Collections List (...));

    4. Stack
    Stack inherits from Vector to implement a post-import, first-out Stack. Stack provides five additional methods to make the Vector used as a Stack. The basic push and pop methods also include the elements of the peek method to get the top of the stack. The empty method tests whether the stack is empty. The search method checks the position of an element in the stack. The Stack is empty after being created.

    Usage:

    1. Package Test;
    2. Import java. util. ArrayList;
    3. Import java. util. Iterator;
    4. Import java. util. List;
    5. Public class TestList {
    6. Public static void main (String dd []) {
    7. // A new storage list
    8. List l = new ArrayList ();
    9. // Because the Collection framework can only store objects, the new encapsulation class
    10. L. add (new Integer (1 ));
    11. L. add (new Integer (2 ));
    12. L. add (new Integer (3 ));
    13. L. add (new Integer (4 ));
    14. Iterator it = l. iterator ();
    15. // Use the Iterator ):
    16. // HasNext is the current value. Its calculation process is to determine whether the next value exists.
    17. While (it. hasNext ()){
    18. System. out. println ("iterator: Element in list is:" + it. next ());
    19. }
    20. // Use the for loop and get () methods:
    21. For (int I = 0; I <l. size (); I ++ ){
    22. System. out. println ("for: Element in list is:" + l. get (I ));
    23. }
    24. }
    25. } Else list

      1. Package Test;
      2. Import java. util. Iterator;
      3. Import java. util. Collections list;
      4. Public class testbench list {
      5. Public static void main (String arg []) {
      6. Counter list ll = new counter list (); // declare the counter list and instantiate it
      7. // Use the add () method to add an element
      8. Ll. add ("");
      9. Ll. add ("B ");
      10. Ll. add ("c ");
      11. // Use the Iterator to traverse the elements of the set and print
      12. Iterator it = ll. iterator ();
      13. While (it. hasNext ()){
      14. System. out. println (it. next ());
      15. }
      16. System. out. println ("------------------");
      17. // Add x and z to the head and end of the linked list respectively.
      18. Ll. addFirst ("z ");
      19. Ll. addLast ("x ");
      20. // View the added result through Traversal
      21. For (Iterator I = ll. iterator (); I. hasNext ();){
      22. System. out. println (I. next ());
      23. }
      24. }
      25. }


        The difference between ArrayList and rule list.

        1. ArrayList is a dynamic array-based data structure. The ArrayList is based on the linked list data structure.

        2. for Random Access to get and set, ArrayList thinks it is better than the sorted list because the sorted list needs to move the pointer.

        3. For add and remove operations, LinedList is dominant because ArrayList needs to move data.

        If you are familiar with the data structure, you will understand that ArrayList is the Sequential Representation of the linear table, and the sorted list is the linked list representation of the linear table.

        5. Set interface, indicating unordered and non-repeated Sets

        Set has the same interface as Collection, so there is no additional function, unlike the previous two different lists. Set is actually 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.

        1. HashSet

        Set designed for quick search. The object stored in the HashSet must define hashCode ().
        2. TreeSet

        The Set that stores the order. The underlying layer is the tree structure. It can be used to extract ordered sequences from the Set.
        3. LinkedHashSet

        Query speed with 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.

        Usage:

        1. Set set = new HashSet ();
        2. String s1 = new String ("hello ");
        3. String s2 = s1;
        4. String s3 = new String ("world ");
        5. Set. add (s1 );
        6. Set. add (s2 );
        7. Set. add (s3 );
        8. System. out. println (set. size (); // The number of objects in the print set is 2.
        9. How does the add () method of Set determine whether the object has been stored in the collection?
        10. Boolean isExists = false;
        11. Iterator iterator = set. iterator ();
        12. While (it. hasNext ()){
        13. String oldStr = it. next ();
        14. If (newStr. equals (oldStr )){
        15. IsExists = true;
        16. }
        17. }

          6. Map interface: ing


          Map does not inherit the Collection interface. Map provides key-to-value ing. You can use the "key" to find the "value ". A Map cannot contain the same key, and each key can only Map one value. The Map interface provides three sets of views. The Map content can be treated as a set of keys, a set of values, or a set of key-value ing.

          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.


          Map also saves a copy of each element, but this is based on the "key". Map also has built-in sorting, so it does not care about the order of element addition. If the order of adding elements is important to you, you should use LinkedHashSet or LinkedHashMap.

          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 the 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 (in the following summary: further discussion is required ). 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.

          1. Hashtable class
          Hashtable inherits the Map interface and implements a key-value ing hash table. Any non-null object can be used as a key or value. Hashtable is synchronous.

          Put (key, value) is used for adding data, and get (key) is used for retrieving data. The time overhead of these two basic operations is constant.
          Hashtable adjusts the performance by initial capacity and load factor. Generally, the default load factor0.75 achieves a better balance between time and space. Increasing the load factor can save space, but the corresponding search time will increase, which affects operations such as get and put.
          A simple example of Hashtable is as follows: Put 1, 2, 3 into Hashtable, and their keys are "one", "two", and "three ":
          Hashtable numbers = new Hashtable ();
          Numbers. put ("one", new Integer (1 ));
          Numbers. put ("two", new Integer (2 ));
          Numbers. put ("three", new Integer (3 ));
          To retrieve a number, such as 2, use the corresponding key:
          Integer n = (Integer) numbers. get ("two ");
          System. out. println ("two =" + n );
          As the key object is determined by calculating its hash function, any object used as the key must implement the hashCode method and equals method. The hashCode and equals Methods inherit from the root class Object. If you use a custom class as the key, be careful. According to the definition of the hash function, if the two objects are the same, that is, if obj1.equals (obj2) = true, their hashCode must be the same, but if two objects are different, their hashCode is not necessarily different. If the hashCode of two different objects is the same, this phenomenon is called a conflict. A conflict will increase the time overhead for operating the hash table. Therefore, the hashCode () method should be defined as much as possible to speed up the operation of the hash table.
          If the same object has different hashCode, operations on the hash table will produce unexpected results (the expected get method returns null). To avoid this problem, you only need to remember one: the equals and hashCode methods must be rewritten at the same time, instead of writing only one of them.
          Hashtable is synchronous.

          2. HashMap class
          Like Hashtable, HashMap is also implemented based on hash. The difference is that HashMap is non-synchronous and allows null, that is, null value and null key ., However, when HashMap is treated as a Collection (the values () method can return the Collection), its iteration suboperation time overhead is proportional to the capacity of HashMap. Therefore, if the performance of iterative operations is very important, do not set the HashMap initialization capacity too high or the load factor too low.

          LinkedHashMap class: 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.

          3. WeakHashMap class (weak key ))
          WeakHashMap is an improved HashMap designed to solve special problems. It implements "weak references" to keys. If a key is no longer referenced by external entities, the key can be recycled by GC.

          4. TreeMap class
          The implementation is 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.

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

          Usage:

          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 (): delete all mappings from the image. 2. query operation:
            Object get (Object key): get 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.
            Conllections: collections class
            Conllections provides static methods for JAVA collections

            7. How to choose

            1. Differences between the container class and Array
            1) 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.
            2) once the object is placed in the container, the type information of the object is lost.

            2,
            1) among various Lists, it is best to use ArrayList as the default choice. Use the sort list () When insertion or deletion is frequent ();
            Vector is always slower than ArrayList, so avoid using it whenever possible.
            2) in various Sets, HashSet is generally better than HashTree (insert and search ). TreeSet is used only when a sorted sequence is generated.
            The only reason for the existence of HashTree is that it can maintain the sorting status of its elements.
            3) in various Maps, HashMap is used for quick search.
            4) when the number of elements is fixed, Array is used because Array is the most efficient.

            Conclusion: ArrayList, HashSet, HashMap, and Array are commonly used. In addition, we will also find a rule in which TreeXXX is sorted.

            Note:

            1. Collection does not have the get () method to obtain 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.
            * Hashing
            The hash code transforms the object information to form a unique int value, which is stored in an array.
            We all know that the array search speed is the fastest in all storage structures. Therefore, the search can be accelerated.

            When a collision occurs, let the array point to multiple values. That is, an orders table is generated at each position of the array.

            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.

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.