First, set frame diagram

Simplified diagram:

Note: There are several explanations for the above frame diagram

All collection classes are located under the java.util package. Java’s Collection classes are derived primarily from two interfaces: Collection and Map, which are the root interfaces of the Java Collection framework, and which in turn contain subinterfaces or implementation classes.

2. Collection interface: Six interfaces (dotted lines), representing different collection types, are the basis of collection framework.

3. Abstract Classes: Five abstract classes (long dashed line) that partially implement the collection interface. Extensible to custom collection classes.

4, implementation class: 8 implementation classes (solid line), the concrete implementation of the interface.

5. The Collection interface is a set of objects that allow repetition.

6. The Set interface inherits Collection without repeating Collection elements.

7. List interface inherits Collection, allowing repetition and maintaining element insertion order.

8. The Map interface is a key-value object and has nothing to do with the Collection interface.

9. Set, List, and Map can be considered as three categories of sets:

  • A List collection is an ordered collection, the elements in the collection can be repeated, and the elements in the collection can be accessed based on the index of the element.
  • A Set is an unordered Set. Elements in a Set cannot be repeated. Elements in a Set can only be accessed based on the elements themselves (which is why elements in a Set are not allowed to be repeated).
  • A Map contains key-value pairs of elements. Only the value of each element can be accessed based on its Key.

2. Overall analysis

General description:

Take a look at the frame diagram above and grab the backbone, Collection and Map.

1. Collection is an interface, which is a highly abstract Collection containing the basic operations and attributes of the Collection. Collection contains two branches: List and Set.

  • A List is an ordered queue, with each element having its index. The first element has an index value of 0. The List implementation classes are LinkedList, ArrayList, Vector, and Stack.
  • A Set is a Set that does not allow duplicate elements. The implementation classes of Set are HastSet and TreeSet. A HashSet relies on a HashMap, and is actually implemented through a HashMap; TreeSet relies on TreeMap and is actually implemented through TreeMap.

2. Map is a mapping interface, that is, key-value pair. Each element in the Map contains a key and a value corresponding to the key. AbstractMap is an abstract class that implements most of the APIS in the Map interface. HashMap, TreeMap, WeakHashMap all inherit from AbstractMap. Although Hashtable inherits from Dictionary, it implements the Map interface.

3. Next, Iterator. It is a tool for iterating over collections, that is, we usually iterate over collections through iterators. We say that a Collection depends on Iterator because each of the Collection’s implementation classes implements an Iterator () function that returns an Iterator object. ListIterator exists specifically for traversing lists.

4. Enumeration, an abstract class introduced in JDK 1.0. Like Iterator, Iterator iterates over collections; But Enumeration has less functionality than Iterator. In the block diagram above, Enumeration can only be used with Hashtable, Vector, and Stack.

Finally, Arrays and Collections. These are two utility classes that operate on arrays and collections.

With the overall framework in place, let’s examine each class individually.

Iii. Collection interface

The Collection interface is the root interface for handling collections of objects and defines many methods for manipulating elements. The Collection interface has two main subinterfaces, List and Set. Keep in mind that Map is not a Collection subinterface.

Methods in the Collection interface are as follows:

! [img] There are several common methods, such as add() to add an element to the collection, addAll() to add all elements from the specified collection to the collection,contains()The toArray() method checks if the collection contains the specified element, and returns an array representing the collection.

In addition, the Collection has an iterator() function that returns an Iterator interface. In general, we iterate over collections by Iterator. ListIterator is specific to the List interface, where ListIterator() returns a ListIterator object.

The Collection interface has two commonly used subinterfaces, described in detail below.

1. The List interface

The List collection represents an ordered collection in which each element has a corresponding sequential index. The List collection allows the use of duplicate elements, which can be accessed by index at a specified location.

The List interface inherits from the Collection interface, which can define an ordered Collection that allows repetition. Because the elements in a List are ordered, we can access the elements in a List by using an index (the position of the element in the List, similar to an array subscript), which is similar to a Java array.

The List interface is the direct interface of Collection. What a List represents is an ordered Collection, that is, it maintains the order of elements with some particular insertion order. The user has precise control over the insertion position of each element in the list, and can access elements based on their integer index (position in the list) and search for elements in the list. List interface implementation of the main set of: ArrayList, LinkedList, Vector, Stack.

(1) the ArrayList

ArrayList is a dynamic array, and the collection we use most often. It allows any element that conforms to the rule to be inserted, including NULL. Each ArrayList has an initial capacity (10) that represents the size of the array. As the number of elements in the container increases, so does the size of the container. A capacity check is performed each time an element is added to the container, and when overflow is imminent, capacity expansion is performed. Therefore, if we know how many elements to insert, it is better to specify an initial capacity value, so as to avoid wasting time and efficiency by too many expansion operations.

Size, isEmpty, get, set, iterator, and listIterator operations all run at a fixed time. The Add operation runs at apportioned fixed time, that is, it takes O(n) time to add n elements (it’s not just that adding elements has apportioned fixed time overhead because of capacity expansion).

Arraylists are good at random access. The ArrayList is also asynchronous.

(2) the LinkedList

LinkedList, which also implements the List interface, is different from ArrayList, which is a dynamic array, and LinkedList, which is a two-way LinkedList. So in addition to the basic operations of ArrayList, it also provides get, remove, insert methods at the beginning or end of LinkedList.

Because of the way it is implemented, LinkedList cannot be accessed randomly, and all operations are performed according to the requirements of a double LinkedList. The operation of an index in a list traverses the list from the beginning or end (from the end close to the specified index). The advantage of this is that you can insert and delete from the List at a lower cost.

Like ArrayList, LinkedList is asynchronous. If multiple threads access a List at the same time, they must implement access synchronization themselves. One solution is to construct a synchronous List when creating a List:

List list = Collections.synchronizedList(new LinkedList(...) );Copy the code

(3) the Vector

Like ArrayList, but Vector is synchronous. So Vector is a thread-safe dynamic array. It operates almost the same as ArrayList.

(4) Stack

Stack inherits from Vector and implements a last-in, first-out Stack. Stack provides five additional methods that allow a Vector to be used as a Stack. The basic push and POP methods, as well as peek to get the element at the top of the stack, empty to see if the stack is empty, and search to see where an element is in the stack. The Stack is empty right after it is created.

2. The Set interface

A Set is a Collection that does not contain repeating elements. It maintains its own internal ordering, so random access doesn’t make any sense. Like List, it also allows null, but only one. Due to the special nature of the Set interface, all elements passed into the Set must be different, and note that any mutable object that causes E1.equals (e2)==true when operating on elements in the Set is bound to cause some problems. The Set interface has three concrete implementation classes, namely HashSet, LinkedHashSet and TreeSet.

A Set is an unordered Collection that contains no duplicate elements, i.e. any two elements E1 and e2 have e1.equals(e2)=false, and a Set has at most one null element.

Note that although the elements in a Set are not ordered, their position in the Set is determined by the element’s HashCode, which is actually fixed.

It should also be noted that there is a special requirement for non-duplication in the SET interface.

For example, object A and object B are two different objects that could normally be put into A Set. However, if object A and object B overwrite hashcode and equals methods, then the overwrite hashcode and equals methods are the same. A and B cannot be added to the Set at the same time.

To better understand, take a look at the following example:

public class Test{ 
public static void main(String[] args) { 
     Set<String> set=new HashSet<String>(); 
     set.add("Hello"); 
     set.add("world"); 
     set.add("Hello"); 
     System.out.println("The set size is :"+set.size()); 
     System.out.println("The elements of the set are :"+set.toString()); }}Copy the code

Running results:

Set size :2 Set elements :[world, Hello]

Analysis: Since the String class overrides the hashCode and equals methods to compare whether the strings stored by the pointed String objects are equal or not. So the second Hello here doesn’t add in.

Here’s another example:

public class TestSet {

    public static void main(String[] args){

        Set<String> books = new HashSet<String>();
        // Add a string object
        books.add(new String("The definitive guide to Struts2"));

        // Add a string object again,
        // Failed to add two string objects because they were compared to be equal using equals, return false
        boolean result = books.add(new String("The definitive guide to Struts2"));

        System.out.println(result);

        // The following output shows that the set has only one elementSystem.out.println(books); }}Copy the code

Running results:

False [Struts2 Authoritative Guide]

The string object added to the book collection twice is clearly not an object (the new keyword is used to create string objects). It returns false when using the == operator and true when comparing equals, so it cannot be added to the Set. Only one element can be output.

(1) the HashSet

A HashSet is a collection of no repeating elements. Implemented by a HashMap, it does not guarantee the order of elements (by out-of-order, I mean the order in which elements are inserted differs from the order in which they are output), and a HashSet allows null elements. A HashSet is asynchronous, and if multiple threads access a HashSet at the same time and at least one of them modifies the set, it must remain externally synchronized. A HashSet stores the elements of a collection using a Hash algorithm, so it has good access and lookup performance.

The implementation of a HashSet is roughly as follows: A HashMap stores elements, which are stored in the Key of the HashMap, and a Value uses an Object Object.

Common mistakes in using and understanding HashSet:

**a. hashset stores null values. ** Nulls are allowed in a HashSet, but only one can be stored in a HashSet.

**b. Hashset stores elements in a fixed location. ** The elements stored in a HashSet are unordered, which is nothing to say, but since the underlying implementation of a HashSet is based on a Hash algorithm using HashCode, the position of the elements in a HashSet is fixed.

C. Mutable objects must be manipulated carefully. This can cause problems if mutable elements in a Set change their state causing object.equals (Object)=true.

(2) LinkedHashSet

LinkedHashSet inherits from HashSet, and its underlying implementation is based on LinkedHashMap, which is ordered and asynchronous. The LinkedHashSet collection also determines where elements are stored based on their hashCode value, but it also maintains the order of elements using a linked list. This makes it appear that the elements are saved in insertion order, that is, when traversing the collection, the LinkedHashSet will access the elements of the collection in the order they were added.

(3) the TreeSet

TreeSet is an ordered collection whose underlying implementation is based on TreeMap and is not thread-safe. TreeSet ensures that collection elements are sorted. **TreeSet supports two sorts, natural and custom, with natural being the default sort. ** When we construct TreeSet, if we use the constructor without parameters, then TreeSet uses the natural comparator; If you want to use a customized comparator, you need to use the parameters with the comparator.

Note: The TreeSet collection does not compare elements using hashcode and equals. Compare compares the ids of two objects. If the ids of two objects are identical, they are considered to be duplicate elements and cannot be added to the set.

4. Map interface

Unlike the List and Set interfaces, a Map is a Set of key-value pairs and provides the mapping between keys and values. It also does not inherit Collection. It ensures a one-to-one correspondence between keys and values in a Map. That is, a key corresponds to a value, so it cannot have the same key value, but of course the value can be the same.

1.HashMap

It is designed for quick query. It defines an array of hash tables (Entry[] table) internally. The element will convert the hash address of the element into the index stored in the array through the hash conversion function. Use a hash list to string together all elements of the same hash address, perhaps by looking at the source code for Hashmap.Entry, which is a single list structure.

2.LinkedHashMap

LinkedHashMap is a subclass of HashMap that preserves the order of inserts, if you want the output to be in the same order as the input.

**LinkedHashMap is a hash table and linked-list implementation of the Map interface with a predictable iteration order. ** This implementation provides all optional mapping operations and allows null values and NULL keys. This class does not guarantee the order of the mapping, and in particular it does not guarantee that the order is constant.

The LinkedHashMap implementation differs from HashMap in that the latter maintains a double-linked list running on all items. This list of links defines the iteration order, which can be either insert order or access order.

According to the order of the elements in the list, it can be divided into: lists in insert order, and lists in access order (call the GET method). The default is sort by insertion order. If you specify sort by access order, then the get method moves the accessed elements to the end of the list.

Note that this implementation is not synchronous. If multiple threads access a linked hash map at the same time, and at least one of them structurally modifies the map, it must remain externally synchronized. LinkedHashMap has slightly lower performance than a HashMap because of its need to maintain the insertion order of elements, but it does a good job iteratively accessing all elements in the Map because it maintains the internal order in a linked list.

3.TreeMap

**TreeMap is an ordered set of key-values that is asynchronous and implemented based on a red-black tree. Each key-value node acts as a node of the red-black tree. **TreeMap sorts key-value pairs by key. There are two types of sorting, either natural or custom, depending on the constructor used.

** Natural ordering: ** All keys in TreeMap must implement the Comparable interface and all keys must be objects of the same class, otherwise a ClassCastException will be reported.

** Custom sort: ** When defining a TreeMap, create a Comparator object that sorts all keys in a TreeMap. The Comparable interface is not required for all keys in a TreeMap to implement a custom sort.

TreeMap’s criterion for determining the equality of two elements: two keys are considered equal if the compareTo() method returns 0.

If you use a custom class as a key in TreeMap and want TreeMap to work well, you must override equals() on the custom class. Both keys return true via equals() and should return 0 by compareTo().


Iterator and ListIterator

1.Iterator

Iterator is defined as follows:

public interface Iterator<E> {}
Copy the code

Iterator is an interface that is an Iterator of a collection. Sets can be iterated through the elements of the set.

Iterator provides the following apis:

  • Boolean hasNext() : Checks whether the next element in the set exists. If so, the hasNext() method returns true.
  • Object Next () : Returns the next element in the collection.
  • Void remove() : removes the element returned by the last next method in the collection.

Example:

public class IteratorExample {
    public static void main(String[] args) {
        ArrayList<String> a = new ArrayList<String>();
        a.add("aaa");
        a.add("bbb");
        a.add("ccc");
        System.out.println("Before iterate : " + a);
        Iterator<String> it = a.iterator();
        while (it.hasNext()) {
            String t = it.next();
            if ("bbb".equals(t)) {
                it.remove();
            }
        }
        System.out.println("After iterate : "+ a); }}Copy the code

The following output is displayed:

Before iterate : [aaa, bbb, ccc] After iterate : [aaa, ccc]

Note:

  • The Iterator can only move in one direction.
  • Iterator.remove() is the only safe way to modify the collection during iteration; If the base set is modified in any other way during the iteration, unknown behavior will result. And every time I call itnext()Method,remove()Methods can only be called once, and an exception will be thrown if this rule is violated.

2.ListIterator

ListIterator is a more powerful Iterator that inherits from the Iterator interface and can only be used for all types of List access. You can call the listIterator() method to produce a listIterator that points to the beginning of the List, or you can call the listIterator(n) method to create a listIterator that starts with an element indexed n in the List.

The ListIterator interface is defined as follows:

public interface ListIterator<E> extends Iterator<E> {
    boolean hasNext(a);

    E next(a);

    boolean hasPrevious(a);

    E previous(a);

    int nextIndex(a);

    int previousIndex(a);

    void remove(a);

    void set(E e);

    void add(E e);

}
Copy the code

From the above definition we can derive ListIterator can:

  • Bidirectional movement (traversing forward/backward).
  • Produces indexes relative to the preceding and following elements of the current position the iterator points to in the list.
  • You can useset()Method replaces the last element it accessed.
  • You can useadd()Methods in thenext()Method to return the element before orprevious()Inserts an element after the element returned by the.

Example:

public class ListIteratorExample {

    public static void main(String[] args) {
        ArrayList<String> a = new ArrayList<String>();
        a.add("aaa");
        a.add("bbb");
        a.add("ccc");
        System.out.println("Before iterate : " + a);
        ListIterator<String> it = a.listIterator();
        while (it.hasNext()) {
            System.out.println(it.next() + "," + it.previousIndex() + "," + it.nextIndex());
        }
        while (it.hasPrevious()) {
            System.out.print(it.previous() + "");
        }
        System.out.println();
        it = a.listIterator(1);
        while (it.hasNext()) {
            String t = it.next();
            System.out.println(t);
            if ("ccc".equals(t)) {
                it.set("nnn");
            } else {
                it.add("kkk");
            }
        }
        System.out.println("After iterate : "+ a); }}Copy the code

The following output is displayed:

Before iterate : [aaa, bbb, ccc]
aaa, 0.1
bbb, 1.2
ccc, 2.3
ccc bbb aaa 
bbb
ccc
After iterate : [aaa, bbb, kkk, nnn]
Copy the code

6. Similarities and differences

1. The ArrayList, and LinkedList

  • ArrayList is a data structure based on dynamic arrays, and LinkedList is a data structure based on linked lists.
  • ArrayList is definitely better than LinkedList for random access to GET and set, because LinkedList moves the pointer.
  • For add and remove operations, LinedList has an advantage because ArrayList moves data.

It depends on the actual situation. ** ArrayList is faster than LinkedList when only single data is inserted or deleted. ** However, when inserting and deleting data randomly in batches, LinkedList is much faster than ArrayList. That’s because each time an ArrayList inserts a piece of data, it moves the insertion point and all subsequent data.

2. The HashTable and HashMap

Similarities:

  • Implement theMap, Cloneable, java.io.SerializableInterface.
  • Are hash tables that store key-value pairs, and are implemented using the zipper method.

Difference:

** (1) Historical reasons: **HashTable is based on the old Dictionary class, and HashMap is an implementation of the Map interface introduced in Java 1.2.

** (2) synchronization: **HashTable is thread safe, that is, synchronous, while HashMap is thread unsafe, not synchronous.

** (3) Handle null values: ** The key and value of a HashMap can be null, and the key and value of a HashTable cannot be null.

** (4) Different base classes: **HashMap inherits from AbstractMap, while Hashtable inherits from Dictionary.

  • Dictionary is an abstract class that inherits directly from the Object class and does not implement any interface. The Dictionary class was introduced in JDK 1.0. Although Dictionary also supports basic operations such as “add key-value pairs”, “get value”, and “get size”, it has fewer API functions than Map. And dictionaries are generally traversed by Enumeration, while maps are traversed by Iterator. However, since Hashtable also implements the Map interface, it supports both Enumeration traversal and Iterator traversal.
  • AbstractMap is an abstract class that implements most of the Map API functions. Provides great convenience for the concrete implementation classes of Map. It is a new class in JDK 1.2.

** (5) Supports different types of traversal: **HashMap only supports Iterator traversal. A Hashtable supports Iterator and Enumeration traversal.

3. Comparison of HashMap, Hashtable, LinkedHashMap and TreeMap

A Hashmap is one of the most commonly used maps that stores data based on the HashCode value of the key, which can be retrieved directly based on the key, with fast access speed. Traversal, the order of data acquisition is completely random. **HashMap allows a Null key for at most one record; Multiple records are allowed to be Null. HashMap does not support thread synchronization, meaning that multiple threads can write a HashMap at any one time. Data inconsistency may result. ** If synchronization is required, the synchronizedMap method of Collections can be used to make HashMap synchronous.

A Hashtable is similar to a HashMap except that it does not allow record keys or values to be null. It supports thread synchronization, meaning that only one thread can write a Hashtable at any one time, thus making the Hashtale slow to write.

The LinkedHashMap stores the insertion order of records. When Iterator traverses the LinkedHashMap, the records obtained first must be inserted first. You can also use parameters to construct the LinkedHashMap and sort the records according to the number of applications. It is slower to traverse than a HashMap, except in cases where HashMap has a large volume and less actual data, it may be slower to traverse than LinkedHashMap, because the traversal speed of LinkedHashMap is only related to the actual data, not the capacity. The traversal speed of a HashMap is related to its capacity.

If you want the output to be in the same order as the input, you can do this with LinkedHashMap, which can also be sorted by read order, as in connection pooling. The LinkedHashMap implementation differs from HashMap in that the latter maintains a double linked list running on all entries. This list of links defines the iteration order, which can be either insert order or access order. In the case of LinkedHashMap, it inherits from HashMap, using hash tables and bidirectional linked lists underneath to hold all elements. The basic operation is similar to that of the parent class HashMap, which implements its linked-list feature by overriding the methods associated with the parent class.

**TreeMap implements the SortMap interface and its internal implementation is a red-black tree. ** can sort its stored records by key, which defaults to an ascending sort of key value, and can specify a sort comparator so that when Iterator traverses a TreeMap, the records are sorted. TreeMap does not allow the key value to be null. Asynchronous.

In general, we use HashMap most. The key-value pair stored in HashMap is random when it is taken out. It stores data according to the HashCode value of the key, and can directly obtain its value according to the key, with fast access speed. A HashMap is the best choice for inserting, deleting, and positioning elements in a Map.

TreeMap pulls out the sorted key-value pairs. But TreeMap is better if you want to traverse the keys in natural or custom order.

LinkedHashMap is a subclass of HashMap. If you want the output order to be the same as the input order, you can use LinkedHashMap. It can also be read in order, as in connection pooling.

import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.TreeMap;

public class MapTest {

    public static void main(String[] args) {

        //HashMap
        HashMap<String,String> hashMap = new HashMap();
        hashMap.put("4"."d");
        hashMap.put("3"."c");
        hashMap.put("2"."b");
        hashMap.put("1"."a");

        Iterator<String> iteratorHashMap = hashMap.keySet().iterator();

        System.out.println("HashMap-->");

        while (iteratorHashMap.hasNext()){

            Object key1 = iteratorHashMap.next();
            System.out.println(key1 + "--" + hashMap.get(key1));
        }

        //LinkedHashMap
        LinkedHashMap<String,String> linkedHashMap = new LinkedHashMap();
        linkedHashMap.put("4"."d");
        linkedHashMap.put("3"."c");
        linkedHashMap.put("2"."b");
        linkedHashMap.put("1"."a");

        Iterator<String> iteratorLinkedHashMap = linkedHashMap.keySet().iterator();

        System.out.println("LinkedHashMap-->");

        while (iteratorLinkedHashMap.hasNext()){

            Object key2 = iteratorLinkedHashMap.next();
            System.out.println(key2 + "--" + linkedHashMap.get(key2));
        }

        //TreeMap
        TreeMap<String,String> treeMap = new TreeMap();
        treeMap.put("4"."d");
        treeMap.put("3"."c");
        treeMap.put("2"."b");
        treeMap.put("1"."a");

        Iterator<String> iteratorTreeMap = treeMap.keySet().iterator();

        System.out.println("TreeMap-->");

        while (iteratorTreeMap.hasNext()){

            Object key3 = iteratorTreeMap.next();
            System.out.println(key3 + "--"+ treeMap.get(key3)); }}}Copy the code

Output result:

HashMap-->
3--c
2--b
1--a
4--d
LinkedHashMap-->
4--d
3--c
2--b
1--a
TreeMap-->
1--a
2--b
3--c
4--d
Copy the code

4. Comparison of HashSet, LinkedHashSet and TreeSet

The Set interface

Set is not allowed to contain identical elements. If you try to add two identical elements to the same collection, add returns false.

The **Set determines that two objects are the same not using the == operator, but based on equals. ** That is, Set will not accept two objects as long as their equals method returns true.

HashSet

HashSet has the following characteristics:

  • The order of elements cannot be guaranteed, and the order may change.
  • It’s not synchronous.
  • Collection elements can be NULL, but only one NULL can be placed.

When storing an element into a HashSet combination, the HashSet calls the object’s hashCode() method to get the object’s hashCode value, which is then used to determine where the object will be stored in the HashSet. To put it simply, a HashSet determines the equality of two elements by comparing them using equals and returning the same value from hashCode().

Note that if you want to put an object into a HashSet and override the equals method of the object’s corresponding class, you should also override its hashCode() method. The rule is that if two objects return true via equals, their hashCode should also be the same. In addition, any property in an object that is used as an Equals comparison standard should be used to calculate the value of hashCode.

LinkedHashSet

The LinkedHashSet collection also determines where elements are stored based on their hashCode value, but it also maintains the order of elements using a linked list. This makes it appear that the elements are saved in insertion order, that is, when traversing the collection, the LinkedHashSet will access the elements of the collection in the order they were added.

LinkedHashSet performs better than HashSet when iteratively accessing all elements in a Set, but performs slightly worse than HashSet when inserted.

The TreeSet class

TreeSet is the only implementation class of the SortedSet interface, and TreeSet ensures that the collection elements are in sorted state. TreeSet supports two sorting modes, natural sorting and custom sorting. Natural sorting is the default sorting mode. Objects of the same class should be added to TreeSet.

TreeSet determines that two objects are not equal if they return false through equals or zero through CompareTo.

Natural ordering

Natural sort uses the CompareTo (Object obj) method of the elements to be sorted to compare the size relationships between the elements, and then ranks the elements in ascending order.

Java provides a Comparable interface that defines a compareTo(Object obj) method that returns an integer value. Objects that implement the Comparable interface can be compared in size. The obj1.compareTo(obj2) method, if it returns 0, indicates that the two objects being compared are equal. If it returns a positive number, it indicates that obj1 is greater than obj2. If it is negative, it indicates that obj1 is less than obj2. If we always return true to equals on both objects, then the compareTo on both objects should return 0.

Custom sorting

Int compare(T o1,T O2) by using the Comparator interface. Compare (T o1,T O2)

package com.test;  

import java.util.HashSet;  
import java.util.LinkedHashSet;  
import java.util.TreeSet;  

/ * * *@description* HashSet: Hash tables store information by using a mechanism called hashing, and the elements are not placed in a particular order; * LinkedHashSet: Maintains a linked list of collections in the order in which elements are inserted, allowing iteration through the collection in the order in which they are inserted; * TreeSet: Provides an implementation of a Set interface that uses a tree structure to store objects in ascending order with fast access and traversal times. *@author Zhou-Jingxian  
 *  
 */  
public class SetDemo {  

    public static void main(String[] args) {  

        HashSet<String> hs = new HashSet<String>();  
        hs.add("B");  
        hs.add("A");  
        hs.add("D");  
        hs.add("E");  
        hs.add("C");  
        hs.add("F");  
        System.out.println("HashSet order: \ n"+hs);  

        LinkedHashSet<String> lhs = new LinkedHashSet<String>();  
        lhs.add("B");  
        lhs.add("A");  
        lhs.add("D");  
        lhs.add("E");  
        lhs.add("C");  
        lhs.add("F");  
        System.out.println("LinkedHashSet order: \ n"+lhs);  

        TreeSet<String> ts = new TreeSet<String>();  
        ts.add("B");  
        ts.add("A");  
        ts.add("D");  
        ts.add("E");  
        ts.add("C");  
        ts.add("F");  
        System.out.println("TreeSet order: \ n"+ts); }}Copy the code

Output result:

[B, A, D, E, C] TreeSet [A, B, C, D, E, F]Copy the code

5. The difference between Iterator and ListIterator

When we use lists and sets, we often use iterators in order to iterate over their data. With iterators, you don’t need to interfere with their traversal, just pull out the data you want to process one at a time. But there are differences in how they are used.

Both lists and sets have iterators () to get their iterators. For lists, you can also get iterators from listIterator(). The two iterators are sometimes incommensurable. The main differences between Iterators and Listiterators are as follows:

  • ListIterator haveadd()Method to add objects to a List that Iterator cannot
  • ListIterator and IteratorhasNext()andnext()Method, you can implement backward traversal, but ListIterator doeshasPrevious()andprevious()Method can be implemented in reverse (sequential forward) traversal. Iterator does not.
  • ListIterator can locate the current index location,nextIndex()andpreviousIndex()It can be done. Iterator does not do this.
  • ListIterator can delete objects, but ListIterator can modify objects,set()Method can be implemented. The Iierator can only be traversed, but cannot be modified.

ListIterator makes it possible to manipulate List data structures such as LinkedList. In fact, array objects can also be implemented using iterators.

6. What is the difference between Collections and Collections

** (1) Java.util. Collection is a Collection interface (a top-level interface of the Collection class). ** It provides generic interface methods for performing basic operations on collection objects. The Collection interface has many concrete implementations in the Java class library. The significance of Collection interface is to provide maximum unified operation mode for various specific collections, and its direct inheritance interfaces are List and Set.

Collection ├List │├LinkedList │├ArrayList │├ exercise │├ Stack ├ SetCopy the code

** (2) Java.util. Collections is a wrapper class (utility class/helper class). ** It contains various static polymorphic methods for collection operations. This class cannot be instantiated and serves as a utility class for sorting, searching, and thread-safe operations on the elements of a Collection in Java’s Collection framework.

Code examples:

import java.util.ArrayList; 
import java.util.Collections; 
import java.util.List; 

public class TestCollections { 

    public static void main(String args[]) { 
        // Note that List implements the Collection interface
        List list = new ArrayList(); 
        double array[] = { 112.111.23.456.231 }; 
        for (int i = 0; i < array.length; i++) { 
            list.add(new Double(array[i])); 
        } 
        Collections.sort(list); 
        for (int i = 0; i < array.length; i++) { 
            System.out.println(list.get(i)); 
        } 
        // Result: 23.0 111.0 112.0 231.0 456.0}}Copy the code

At the end of the article’s welfare

Liver the whole network, 43 Copies of Java mind map, need to take!! !

Java Interview Manual V1.0, free in hd PDF