Java Collection Framework

As far back as Java 2, Java provided ad hoc classes. For example: Dictionary, Vector, Stack, and Properties These classes are used to store and manipulate object groups.
Although these classes are very useful, they lack a core, unified theme. For this reason, using the Vector class is very different from 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, works in a similar manner, and is highly interoperable.
  • The expansion and adaptation of a set must be simple.
For this reason, the entire collection framework is designed around a set of standard interfaces. You can use the standard implementations of these interfaces directly, such as: LinkedList, HashSet, and TreeSet, among others. You can also implement your own collections through these interfaces.
The collection framework is a unified architecture used to represent and manipulate collections. All collection frameworks include the following:
  • Interface: is an abstract data type that represents a collection. The interface allows the collection to independently manipulate the details it represents. In object-oriented languages, interfaces usually form a hierarchy.
  • Implementation (class): A concrete implementation of a collection interface. In essence, they are reusable data structures.
  • Algorithms: Some useful calculations performed by methods in objects that implement collection interfaces, such as: search and sort. These algorithms are called polymorphic because the same method can have different implementations on similar interfaces.
In addition to the collection, the framework also defines several Map interfaces and classes. Map stores key/value pairs. Although Maps are not collections, they are fully integrated in the collection.

Collection frame system as shown


The Java Collections Framework provides a set of well-proven, easy-to-use interfaces and classes. The Java Collections Framework is located in the java.util package, so when using the collections framework, you need to perform the package.

Collection interface

The collection framework defines some interfaces. This section provides an overview of each interface:
No.Interface description
1Collection interface
Collection is the most basic collection interface, a Collection represents a group of Object, the elements of the Collection, Java does not provide a class that inherits directly from the Collection, only to provide inherited sub-interfaces (such as List and set).
2List interface
The List interface is an ordered Collection that uses this interface to precisely control where each element is inserted. It can access elements in the List by indexing (the element's position in the List, similar to an array's subscript). The index of the element is 0, and the same element is allowed.
3Set
Set has exactly the same interface as Collection, but it is different in behavior. Set does not save duplicate elements.
4SortedSet 
inherits from Set's ordered collection.
5Map 
maps unique keys to values.
6Map.Entry 
describes an element (key/value pair) in a Map. Is an internal class of Map.
7SortedMap 
inherits from Map, keeping Key in ascending order.
8Enumeration 
This is a traditional interface and defined method by which you can enumerate (get one at a time) the elements in a collection of objects. This traditional interface has been replaced by iterators.

The difference between Set and List

  • 1. The Set interface instance stores unordered, non-repeated data. The List interface instance stores ordered, repeatable elements.
  • 2. Set retrieval is inefficient, removal and insertion efficiency is high, insertion and deletion do not cause the element position to change <implementation class HashSet, TreeSet> .
  • 3. List and array are similar and can grow dynamically. The length of List is automatically increased according to the length of the actually stored data. Finding elements is efficient, inserting deletes is inefficient because it causes other element positions to change <implementation class has ArrayList,LinkedList,Vector> .

Collection implementation class (collection class)

Java provides a set of standard collections that implement the Collection interface. Some of these are concrete classes that can be used directly, while others are abstract classes that provide partial implementation of the interface.
The standard collection classes are summarized in the following table:
No.Class 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 rather than random access.
4LinkedList
This class implements the List interface, allowing null (empty) elements. Mainly used to create a linked list data structure, this class does not have a synchronization method, if multiple threads access a List at the same time, you must achieve their own access synchronization, the solution is to create a synchronized List when creating the List. E.g:
Listlist=Collections.synchronizedList(newLinkedList(...));
= Collections . synchronizedList ( newLinkedList (...));
LinkedList search efficiency is low.
5ArrayList
This class also implements the List interface, implements variable-size arrays, and 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 50% of the current length, and insertion and deletion are inefficient.
6AbstractSet 
inherits from AbstractCollection and implements most of the Set interface.
7HashSet
This class implements the Set interface, does not allow duplicate elements, does not guarantee the order of the elements in the set, and allows elements containing null values, but only one at most.
8The LinkedHashSet 
has  a hash table and linked list implementation of the Set interface with predictable iteration order  .
9TreeSet
This class implements the Set interface and can perform sorting and other functions.
10AbstractMap 
implements most of the Map interface.
11HashMap 
HashMap is a hash table that stores key-value mappings. 
This class implements the Map interface, stores data based on the hash value of the key, has a very fast access speed, allows a maximum of one record key to be null, does not support thread synchronization.
12TreeMap 
inherits AbstractMap and uses a tree.
13WeakHashMap 
extends the AbstractMap class and uses a weak key hash table.
14LinkedHashMap 
inherits from HashMap and uses the natural ordering of elements to sort elements.
15IdentityHashMap 
extends the AbstractMap class and uses reference equality when comparing documents.
The classes defined in the java.util package have been discussed in previous tutorials as follows:
No.Class description
1Vector 
This class is very similar to ArrayList, but the class is synchronous and can be used in multi-threaded situations. This class allows you to set the default growth length. The default expansion method is 2 times the original.
2Stack 
is a subclass of Vector that implements a standard last-in, first-out stack.
3The Dictionary 
Dictionary class is an abstract class that stores 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 hold bit values. The size of the array in BitSet will increase as needed.

Collection algorithm

The collection framework defines several algorithms that can be used for collections and mappings. These algorithms are defined as static methods of collection classes.
Some methods can throw a ClassCastException when trying to compare incompatible types. When attempting to modify an unmodifiable collection, an UnsupportedOperationException is thrown.
The set defines three static variables: EMPTY_SET, EMPTY_LIST, and EMPTY_MAP. None of these variables can be changed.
No.Algorithm Description
1Collection Algorithms 
Here is a list of all algorithm implementations.

How to use iterators

Normally, you will want to iterate through the elements of a collection. For example, each element in the collection is displayed.
Generally iterating through arrays uses for loops or enhancements. These two methods can also be used in collections frameworks, but there is a way to use iterators to iterate over a collection framework, which is an object that implements the Iterator interface or the ListIterator interface.
Iterators allow you to get or remove elements of a collection through loops. ListIterator inherits Iterator to allow two-way traversal of lists and modification of elements.
No.Iterator method description
1Using Java Iterator 
This lists all methods provided by the Iterator and listIterator interfaces through an instance.

Traversing an ArrayList

Examples

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"); // first traversal method using foreach traversal List for ( String str : list ) {
// Also rewrite for(int i=0;i<list.size();i++) System . out . println ( str ) ; }

// A second type of traversal, traversing lists 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) This form { System . out . println ( strArray [ i ] ) ; }

//The third traversal uses an iterator for related traversal Iterator < String > ite = list . iterator ( ) ;
while ( ite . hasNext ( ) ) // Judge the next element has a value {
System . out . println ( ite . next ( ) ) ; }
}
}
Hello
World
HAHAHAHA
Hello
World
HAHAHAHA
Hello
World
HAHAHAHA

Analysis:
All three methods are used to iterate over the ArrayList collection. The third method is to use the iterator method, which does not have to worry about going beyond the collection's length during traversal.

Traverse the Map

Examples

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"); // first: the widespread use of secondary value System . out . println ( " Mapping key and value via Map.keySet: " ) ; for ( String key : map . keySet ( ) ) {
System.out.println(" key= " + key + " and value= " + map.get( key ) ) ; }
// second System.out.println(" Using iterator over Map.entrySet to traverse keys and values:");
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()); }
// Third: Recommended, especially large Time System . out . println ( " Mapping key and value via Map.entrySet " ) ; for (Map.Entry<String, String> entry : map.entrySet()) { System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue()); } // Fourth System . out . println ( " Iterates over all values ​​via Map.values(), but not through key " ) ; for (String v : map.values()) { System.out.println("value= " + v); }
}
}

 Mapping key and value via Map.keySet: 
 key= 3 and value= value3
 key= 2 and value= value2
 key= 1 and value= value1
 Using iterator over Map.entrySet to traverse keys and values:
key= 3 and value= value3
key= 2 and value= value2
key= 1 and value= value1
 Mapping key and value via Map.entrySet 
key= 3 and value= value3
key= 2 and value= value2
key= 1 and value= value1
 Iterates over all values ​​via Map.values(), but not through key 
value= value3
value= value2
value= value1


How to use the comparator

The TreeSet and TreeMap store the elements in a sorted order. However, this is precisely what the sort order is based on by the comparator.
This interface allows us to sort a collection in different ways.
No.Comparator method description
1Use the Java Comparator to 
list all methods provided by the Comparator interface by instance

to sum up

The Java Collection Framework provides programmers with prepackaged data structures and algorithms to manipulate them.
A collection is an object that can hold references to other objects. Collection interfaces declare actions that can be performed on each type of collection.
The collection framework's classes and interfaces are in the java.util package.
After any object is added to a collection class, it is automatically converted to an Object type, so when it is taken out, it needs to be cast.

Comments