Collection framework
long before Java 2, Java provided special classes (such as Vector, Stack and Properties) to store and manipulate object groups. While these classes are very useful, they lack a core, unified theme. Therefore, the way you use the Vector class is very different from the way you use the Properties class.
set framework is a unified architecture used to represent and operate sets. All set frameworks include the following contents:
- Interface: an abstract data type representing a collection. Interfaces allow collections to manipulate the details they represent independently. In object-oriented languages, interfaces usually form a hierarchy.
- Implementation (class): the concrete implementation of the collection interface. Essentially, they are reusable data structures.
- Algorithm: some useful calculations performed by methods in objects that implement the collection interface, such as search and sorting. These algorithms are called polymorphic because the same method can have different implementations on similar interfaces.
In addition to collections, the framework also defines a Map interface. Although maps are not collections, they are fully integrated in collections.
the collection framework is designed to meet the following objectives:
- The framework must be high performance. The implementation of basic sets (dynamic array, linked list, tree, hash table) must also be efficient.
- The framework allows different types of collections to work in a similar way and has a high degree of interoperability.
- The extension and adaptation of a collection must be simple.
Therefore, the whole collection framework is designed around a set of standard interfaces. You can directly use the standard implementations of these interfaces, such as LinkedList, HashSet and TreeSet. In addition, you can also implement your own collection through these interfaces.
the collection framework system is shown in the figure:
Java collection framework provides a set of interfaces and classes with excellent performance and easy to use. It is located in Java Util package, so you need to import the package when using the collection framework.
Collection interface
the collection framework defines some interfaces:
- Collection: 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 directly inherited from collection, but only sub interfaces inherited from (such as List and set).
- List: the list interface is an ordered Collection. Using this interface, you can accurately control the insertion position of each element and access the elements in the list through the index (the position of the element in the list, similar to the subscript of the array). The index of the first element is 0, and the same element is allowed.
- Set: set has exactly the same interface as Collection, but the behavior is different. Set does not save duplicate elements.
- SortedSet: inherits from Set and saves ordered sets.
- Map: Map unique keys to values.
- Map.Entry: describes an element (key value pair) in a map. It is the internal class of the map.
- SortedMap: inherited from the Map to keep the keys in ascending order.
- Enumeration: This is a traditional interface and defined method, through which you can enumerate (get one at a time) the elements in the object collection. This traditional interface has been replaced by iterators.
difference between Set and List:
- The Set interface instance stores unordered and non duplicate data. The List interface instance stores ordered and repeatable elements.
- Set has low retrieval efficiency and high deletion and insertion efficiency. Insertion and deletion will not cause element position change (implementation classes include HashSet and TreeSet).
- List is similar to array. It can grow dynamically and automatically increase the length of list according to the length of actually stored data. The efficiency of finding elements is high, and the efficiency of inserting and deleting elements is low, because it will cause the position of other elements to change (the implementation classes are ArrayList, LinkedList and 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 implementation of the interface:
- AbstractCollection: implements most collection interfaces.
- AbstractList: inherits from AbstractCollection and implements most of the List interfaces.
- AbstractSequentialList: inherited from AbstractList, it provides chain access to data elements instead of random access.
- LinkedList: this class implements the List interface and allows null elements. It is mainly used to create linked List data structures. LinkedList lookup is inefficient. This class does not have a synchronization method. If multiple threads access a List at the same time, they must synchronize their access. The solution is to construct a synchronized List when creating a List:
Listlist = Collections.synchronizedList(newLinkedList(...));
- ArrayList: this class also implements the interface of List. It is also a variable size array. It provides better performance when randomly accessing and traversing elements. This class is also asynchronous and should not be used in the case of multithreading. ArrayList increases by 50% of the current length, and the insertion and deletion efficiency is low.
- AbstractSet: inherits from AbstractCollection and implements most Set interfaces.
- HashSet: this class implements the Set interface. Duplicate elements are not allowed, and the order of elements in the collection is not guaranteed. It is allowed to contain elements with null values, but there can only be one at most.
- LinkedHashSet: hash table and link list implementation of Set interface with predictable iteration order.
- TreeSet: this class implements the Set interface, which can realize sorting and other functions.
- AbstractMap: implements most of the Map interfaces.
- HashMap: a HashMap is a hash table that stores key value mappings. This class implements the Map interface, stores data according to the HashCode value of the key, has fast access speed, allows at most one record key to be null, and does not support thread synchronization.
- TreeMap: inherits from AbstractMap and uses a tree.
- WeakHashMap: inherits from AbstractMap class and uses hash table with weak key.
- LinkedHashMap: inherits from the HashMap class and uses the natural order of elements to sort elements.
- IdentityHashMap: inherits from AbstractMap class and is used when comparing documents.
java. The classes defined in the util package are as follows:
- Vector: this class is very similar to ArrayList, but it 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 twice the original.
- Stack: stack is a subclass of Vector, which implements a standard last in first out stack.
- Hashtable: hashtable is a subclass of the Dictionary class, located in Java Util package.
- Properties: properties inherits from Hashtable and represents a persistent property set. Each key and its corresponding value in the property list are a string.
- BitSet: a BitSet class creates a special type of array to hold bit values. The array size in BitSet will increase as needed.
Set algorithm
The set framework defines several algorithms that can be used for sets and mappings. These algorithms are defined as static methods of collection classes. Some methods can throw ClassCastException exceptions when trying to compare incompatible types. An unsupported operationexception is thrown when trying to modify a collection that cannot be modified.
The set defines three static variables: EMPTY_SET,EMPTY_LIST and EMPTY_MAP, these variables cannot be changed.
How to use iterators
usually, you want to traverse the elements in a collection, such as displaying each element in the collection. Generally, for loops or enhanced for are used to traverse arrays. These two methods can also be used in the collection framework. But another way is to use iterators to traverse the collection framework, which is an object that implements the Iterator interface or the ListIterator interface.
Iterators enable you to get or delete elements of a collection through a loop. ListIterator inherits Iterator to allow two-way traversal of lists and modification of elements:
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"); /* Use foreach to traverse the List, which can also be written as "for (int i = 0; I < List. Size(); I + +)" */ for (String str : list) { System.out.println(str); } /* Change the linked list into an array and traverse the related contents */ String[] strArray = new String[list.size()]; list.toArray(strArray); /* It can also be rewritten as "foreach(String str:strArray)" */ for (int i = 0; i < strArray.length; i++) { System.out.println(strArray[i]); } Iterator<String> ite = list.iterator(); /* Related traversal using iterators */ while (ite.hasNext()) { /* Determine whether there is a value after the next element */ System.out.println(ite.next()); } } }
The three methods are used to traverse the ArrayList set. The third method is the iterator method, which can avoid exceeding the length of the set in the process of traversal.
traverse the Map as follows:
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 kind */ System.out.println("adopt Map.keySet ergodic key and value: "); for (String key : map.keySet()) { System.out.println("key = " + key + " and value = " + map.get(key)); } /* Second */ System.out.println("adopt Map.entrySet use iterator ergodic key and value: "); 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: this method is recommended, especially when the capacity is large */ System.out.println("adopt Map.entrySet ergodic key and value"); for (Map.Entry<String, String> entry : map.entrySet()) { System.out.println("key = " + entry.getKey() + " and value = " + entry.getValue()); } /* Fourth */ System.out.println("adopt Map.values Traverse all value,But it cannot be traversed key"); for (String v : map.values()) { System.out.println("value = " + v); } } }
Execution results:
adopt Map.keySet ergodic key and value: key = 1 and value = value1 key = 2 and value = value2 key = 3 and value = value3 adopt Map.entrySet use iterator ergodic key and value: key = 1 and value = value1 key = 2 and value = value2 key = 3 and value = value3 adopt Map.entrySet ergodic key and value key = 1 and value = value1 key = 2 and value = value2 key = 3 and value = value3 adopt Map.values Traverse all value,But it cannot be traversed key value = value1 value = value2 value = value3