set

set

 

Long before Java 2, Java provided ad hoc classes. For example: Dictionary, Vector, Stack, and Properties classes are used to store and manipulate object groups. Although these classes are very useful, they lack a core, unified theme. For this reason, the way of using the Vector class is very different from the way of using the Properties class.

The collection framework is designed to meet the following goals.

  • The framework must be high-performance. The implementation of basic collections (dynamic arrays, linked lists, trees, hash tables) must also be efficient.
  • The framework allows different types of collections to work in similar ways with a high degree of interoperability.
  • The expansion and adaptation of a collection must be simple.

For this reason, the entire collection framework is designed around a set of standard interfaces. You can directly use the standard implementations of these interfaces, such as:  LinkedListHashSet , and  TreeSet,  etc. In addition, you can also implement your own collections through these interfaces.

As can be seen from the above collection framework diagram, the Java collection framework mainly includes two types of containers, one is a collection, which stores a collection of elements, and the other is a map, which stores key/value pair mappings. The Collection interface has 3 subtypes, List, Set, and Queue. Below are some abstract classes. Finally, there are concrete implementation classes. Commonly used are ArrayList, LinkedList, HashSet, LinkedHashSet, HashMap, LinkedHashMap, and so on.

The collection framework is a unified framework for representing and manipulating collections. All collection frames include the following:

  • Interface: is an abstract data type representing a collection. For example, Collection, List, Set, Map, etc. The reason for defining multiple interfaces is to manipulate collection objects in different ways
  • Implementation (class): It is the concrete realization of the collection interface. Essentially, they are reusable data structures, such as: ArrayList, LinkedList, HashSet, HashMap.
  • Algorithm: Some useful calculations performed by methods in objects that implement the collection interface, such as searching and sorting. These algorithms are called polymorphism, because the same method can have different implementations on similar interfaces.

In addition to collections, the framework also defines several Map interfaces and classes. What is stored in the Map are key/value pairs. Although Maps are not collections, they are fully integrated in collections.

The collective framework system is shown in the figure

The Java collection framework provides a set of interfaces and classes with excellent performance and easy to use. The java collection framework is located in the java.util package, so when using the collection framework, you need to guide the package.


Collection interface

The collection framework defines some interfaces. This section provides an overview of each interface:

Serial numberInterface description
1Collection interface Collection is the most basic collection interface. A Collection represents a group of Objects, that is, the elements of the Collection. Java does not provide classes that directly inherit from Collection, but only provides sub-interfaces (such as List and set) that inherit from. The Collection interface stores a set of non-unique, unordered objects.
2List interface The List interface is an ordered Collection. Using this interface, you can precisely control the position where each element is inserted, and you can access the elements in the List by index (the position of the element in the List, similar to the subscript of the array). The index of an element is 0, and the same elements are allowed. The List interface stores a set of non-unique, ordered (insertion order) objects.
3SetSet has exactly the same interface as Collection, but the behavior is different. Set does not store duplicate elements. The Set interface stores a set of unique, unordered objects.
4SortedSet inherits from Set to store an ordered collection.
5The MapMap interface stores a set of key-value objects and provides a key (key) to value (value) mapping.
6Map.Entry describes an element (key/value pair) in a Map. It is an internal class of Map.
7SortedMap inherits from Map, keeping the Key in ascending order.
8Enumeration This is a traditional interface and defined method through which you can enumerate (obtain one at a time) elements in a collection of objects. This traditional interface has been replaced by iterators.
package com.design; import java.util.*; public class SetFramework { public static void main (String[] args) { /** * List interface stores a group of not unique * Ordered (insertion order) objects. */ List<String> list = new ArrayList<>(); list.add( "1" ); list.add( "2" ); list.add( "1" ); System.out.println(list.size()); System.out.println(list); /** * Set does not save duplicate elements. * The Set interface stores a set of unique, unordered objects. */ Set<String> Setlist = new HashSet<>(); Setlist.add( "4000" ); Setlist.add( "1000" ); Setlist.add( "1000" ); Setlist.add( "2000" ); System.out.println(Setlist.size()); System.out.println(Setlist); Iterator iterSet = Setlist.iterator(); while (iterSet.hasNext()) { System.out.println(iterSet.next()); } /** * Inherited from Set to save an ordered collection. */ SortedSet <String> SortedSetlist = new TreeSet<>(); SortedSetlist.add( "4000" ); SortedSetlist.add( "1000" ); SortedSetlist.add( "1000" ); SortedSetlist.add( "2000" ); System.out.println(SortedSetlist.size()); System.out.println(SortedSetlist); Iterator iterSortedSet = SortedSetlist.iterator(); while (iterSortedSet.hasNext()) { System.out.println(iterSortedSet.next()); } /** * The Map interface stores a set of key-value objects * Provide key (key) to value (value) mapping. */ Map map = new HashMap(); map.put( "22" , "2222" ); map.put( "55" , "5555" ); map.put( "88" , "8888" ); map.put( "33" , "3333" ); System.out.println(map); /** * Describe an element (key/value pair) in a Map * Is an internal class of Map. */ } } Copy code

The difference between Set and List

  • 1. The instance of the Set interface stores out-of-order, non-repetitive data. The List interface instance stores ordered and repeatable elements.
  • 2. Set retrieval efficiency is low, deletion and insertion efficiency is high, insertion and deletion will not cause element position change  <implementation class has HashSet, TreeSet> .
  • 3. List is similar to array, which can grow dynamically, and automatically grow the length of List according to the length of the actual stored data. The efficiency of finding elements is high, and the efficiency of inserting and deleting is low, because it will cause the position of other elements to change.  <Implementation classes are ArrayList, LinkedList, Vector>  .

Collection implementation class (collection class)

Java provides a set of standard collection classes that implement the Collection interface. Some of them are concrete classes that can be used directly, while others are abstract classes that provide partial implementations of interfaces.

The standard collection classes are summarized in the following table:

Serial numberClass description
1AbstractCollection implements most of the collection interfaces.
2AbstractList inherits from AbstractCollection and implements most of the List interface.
3AbstractSequentialList inherits from AbstractList and provides chained access to data elements instead of random access.
4LinkedList This class implements the List interface and allows null (empty) elements. It is mainly used to create a linked list data structure. This class has no synchronization method. If multiple threads access a List at the same time, you must implement the access synchronization yourself. The solution is to construct a synchronized List when creating the List. For example: ```html
Listlist=Collections.synchronizedList(newLinkedList(...));
```LinkedList search efficiency is low.
5ArrayList This class also implements the List interface, which implements a variable-size array, which provides better performance when randomly accessing and traversing elements. This class is also asynchronous and should not be used in multi-threaded situations. ArrayList grows by 50% of the current length, and the insertion and deletion efficiency is low.
6AbstractSet inherits from AbstractCollection and implements most of the Set interface.
7This class of HashSet implements the Set interface, does not allow duplicate elements, does not guarantee the order of elements in the set, and allows to contain elements with a value of null, but only one at most.
8LinkedHashSet has a hash table and linked list implementation of the Set interface with predictable iteration order.
9The TreeSet class implements the Set interface, which can implement sorting and other functions.
10AbstractMap implements most of the Map interface.
11HashMap HashMap is a hash table, which stores key-value pairs (key-value) mapping. This class implements the Map interface, stores data according to the HashCode value of the key, and has a fast access speed. At most, the key of one record is allowed to be null, and thread synchronization is not supported.
12TreeMap inherits AbstractMap and uses a tree.
13WeakHashMap inherits the AbstractMap class and uses a hash table with weak keys.
14LinkedHashMap inherits from HashMap and uses the natural order of the elements to sort the elements.
15IdentityHashMap inherits the AbstractMap class and uses reference equality when comparing documents.

In the previous tutorial, the classes defined in the java.util package have been discussed, as shown below:

Serial numberClass description
1Vector This class is very similar to ArrayList, but this class is synchronous and can be used in multi-threaded situations. This class allows setting the default growth length, and the default expansion method is twice the original.
2Stack Stack is a subclass of Vector, which implements a standard last-in first-out stack.
3Dictionary The Dictionary class is an abstract class used to store key/value pairs, similar to the Map class.
4Hashtable Hashtable is a subclass of the Dictionary class and is located in the java.util package.
5Properties Properties inherits from Hashtable and represents a persistent set of properties. Each key and its corresponding value in the property list is a string.
6BitSet A Bitset class creates a special type of array to store bit values. The size of the array in the BitSet will increase as needed.

Ensemble algorithm

The collection framework defines several algorithms that can be used for collection and mapping. These algorithms are defined as static methods of the collection class.

Some methods can throw ClassCastException when trying to compare incompatible types. When trying to modify an unmodifiable collection, an UnsupportedOperationException is thrown.

The collection defines three static variables: EMPTY_SET, EMPTY_LIST, EMPTY_MAP. None of these variables can be changed.

 

Serial numberAlgorithm Description
1Collection Algorithms Here is a list of all algorithm implementations.

How to use iterators

Normally, you will want to traverse the elements in a collection. For example, show every element in the collection.

Generally, traversing arrays uses for loops or enhanced for. These two methods can also be used in the collection framework, but there is another method to traverse the collection framework by using iterators. It is an object that implements the Iterator interface or the ListIterator interface.

Iterators enable you to get or delete elements of the collection through loops. ListIterator inherits Iterator to allow bidirectional traversal of lists and modification of elements.

Serial numberIterator method description
1Using Java Iterator Here are examples of all the methods provided by the Iterator and listIterator interfaces.

Iterate over the ArrayList

Instance

import java.util.*; public class Test { public static void main (String[] args) { List<String> list = new ArrayList<String>(); list.add( "Hello" ); list.add( "World" ); list.add( "HAHAHAHA" ); //The first traversal method uses foreach to traverse the List for (String str: list) { //You can also rewrite for(int i=0;i<list.size();i++) This form System.out.println(str); } //The second type of traversal is to traverse the linked list into array-related content String[] strArray = new String[list.size()]; list.toArray(strArray); for ( int i = 0 ;i<strArray.length;i++) //This can also be rewritten as foreach(String str:strArray) { System.out.println(strArray[i]); } //The third type of traversal uses an iterator for related traversal Iterator<String> ite=list.iterator(); while (ite.hasNext()) //Judging that there is a value after the next element { System.out.println(ite.next()); } } } Copy code

 

Analysis:

The three methods are used to traverse the ArrayList collection, the third method is to use the iterator method, this method does not have to worry about exceeding the length of the collection during the traversal process.

Traverse the Map

Instance

import java.util.*; public class Test { public static void main (String[] args) { Map<String, String> map = new HashMap<String, String>(); map.put( "1" , "value1" ); map.put( "2" , "value2" ); map.put( "3" , "value3" ); //The first type: commonly used, secondary value System.out.println( "traverse key and value through Map.keySet:" ); for (String key: map.keySet()) { System.out.println( "key = " + key + " and value = " + map.get(key)); } //The second System.out.println( "Use iterator to traverse key and value through Map.entrySet:" ); Iterator<Map.Entry<String, String>> it = map.entrySet().iterator(); while (it.hasNext()) { Map.Entry<String, String> entry = it.next(); System.out.println( "key= " + entry.getKey() + " and value= " + entry.getValue()); } //The third type: recommended, especially when the capacity is large System.out.println( "traverse key and value through Map.entrySet" ); for (Map.Entry<String, String> entry: map.entrySet()) { System.out.println( "key = " + entry.getKey() + " and value = " + entry.getValue()); } //The fourth System.out.println( "traverse all values through Map.values(), but not key" ); for (String v: map.values()) { System.out.println( "value= " + v); } } } Copy code

 


How to use the comparator

TreeSet and TreeMap store elements in sorted order. However, this is exactly what sort order is defined by the comparator.

This interface allows us to sort a collection in different ways.

Serial numberComparator method description
1Use Java Comparator Here to list all the methods provided by the Comparator interface through examples

summary

The Java collection framework provides programmers with pre-packaged data structures and algorithms to manipulate them.

A collection is an object that can hold references to other objects. The collection interface declares the operations that can be performed on each type of collection.

The classes and interfaces of the collection framework are in the java.util package.

After any object is added to the collection class, it is automatically converted to the Object type, so when it is taken out, a forced type conversion is required.