Note: This article is based on JDK 1.7
1 overview
Java provides a rich collection framework that contains many interfaces, virtual classes, and implementation classes. These interfaces and classes provide rich functionality to meet basic aggregation requirements. Is the overall structure of this framework:
As you can see, the frame is very large and surprisingly large. The left part of the graph is the interface, the right part is the class, the middle line represents the right side of the class to realize which interfaces on the left. For example, the Abstractlist class implements the list interface, and the subclass that inherits from the Abstractlist class implements this interface. Also, if a class implements an interface, this class also implements all the parent interfaces of the interface. For example, the TreeSet class implements the Deque interface, so the TreeSet class also implements the queue interface, collection interface, and Iterable interface (the interface collection expands iterable, which is not shown here).
The red class in the figure represents an abstract class, and most abstract classes begin with abstract except dictionary. The green-colored classes represent legacy classes that already existed at the beginning of Java.
2 Interface and implementation separation
The Java Collection Class library separates the interface (interface) from the implementation (implementation). Here is an example of a queue.
The queue interface indicates that elements can be added at the end of the queue, elements are deleted at the head of the queue, and the number of elements in the queue can be found. That is, the elements in the queue use the queue in terms of first-out elements.
If we design the queue interface, this might be the design:
Interface queue<e>{ void Add (E element); E remove (); int size ();}
Here are three basic methods. This interface does not give the queue how it should be implemented. In general, there are two ways to implement a queue: one is to use a loop array, and the other is to use a linked list.
You need to point to the head and tail tail when using the loop array;
Class Circulararrayqueue<e> implements queue<e>{ circulararrayqueue (int capacity) {...} public void Add (E Element) {...} Public E Remove () {...} Private e[] elements; private int head; private int tail;} Class Linkedlistqueue<e> implements queue<e>{ Linkedlistqueue () {...} public void Add (E Element) {...} Public E Remove () {...} public int size () {...} Private Link head; Private Link Tail;}
The above is just a simple queue of our own implementation, the Java class Library does not have these two classes. When you need to use a queue, you can use the LinkedList class, which implements the queue interface.
When using queues in a program, once a collection is built, you do not need to know exactly which implementation is being used. Therefore, it is only meaningful to use a specific class when building a collection object. You can use an interface type to hold a reference to a collection:
Queue<employee> employee=new circulararrayqueue<> (+); Employee.add (New Employee ("Harry"));
This way, once you have changed your mind, you can easily use another different implementation. You only need to make changes to one place in the program, that is, where the constructor is called. If you feel that Linkedlistqueue is a better choice, you can modify it like this:
Queue<employee> employee=new linkedlistqueue<> (); Employee.add (New Employee ("Harry"));
The interface itself does not give a specific implementation, so it is not possible to give any implementation more in line with the actual application. In this way, the choice of which implementation needs to be chosen by the programmer. There are many classes implemented in the Java class Library, each with its own features and the applicable scenarios, and perhaps some of the implementations are better than one, but may also pay a price on another feature. How to balance the cost of each performance needs to be grasped by the class library users themselves.
In, we can find a lot of red classes that begin with abstract, which are abstractions that are designed for class library implementations that implement some basic methods. If you want to implement your own queue class, you will find it more convenient to extend the Abstractqueue analogy to implement the queue interface.
3 collection interfaces and iterator interfaces in Java class libraries
In the Java class Library, the basic interface of the collection class is the collection interface. The following two methods are available in this interface:
Boolean Add (E Element);iterator<e> Iterator ();
Of course, there are other methods in addition to these two methods, which are described later.
The Add method is used for adding elements to the collection, and returns True if the added element does change the collection, or False if the collection does not change.
The iterator method is used to return an object that implements the iterator interface. You can use this iterator object to access the elements in the collection in turn.
Here's an introduction to the important iterators in the Java class Library.
The iterator iterator interface has three methods:
public interface iterator<e>{ E next (); Boolean hasnext (); void Remove ();
By repeatedly invoking the next method, each element in the collection can be accessed individually. But if the end of the collection is reached, the next method throws a Nosuchelementexception exception. Therefore, you should call the Hasnext method before calling the next method. This method returns true if the iterator object has more than one element to access. Therefore, you can access all the elements in the collection by using the following methods:
Collection<string> c=...;iterator<string> It=c.iterator (); while (It.hasnext ()) { String element= It.next (); Do something with element}
From Jave SE 5.0, you can also iterate through all the elements in the collection using the For each:
for (String element:c) {does something with element}
The compiler simply translates this for Each loop into a loop with an iterator.
The For Each loop can work with any object that implements the Iterable interface, which contains only one method:
public interface iterable<e>{ iterator<e> Iterator ();}
The collection interface extends the Iterable interface, so you can use a For Each loop for any collection in the standard library.
It is important to note that the order in which elements are accessed depends on the type of collection. If you iterate over the ArrayList, the iterator will start at index 0, each iteration, and the index value plus 1. However, if you access the elements in HashSet, each element will appear in a random order. Although it can be determined that all elements can be traversed during the iteration, it is not possible to predict the order in which the elements are accessed.
Iterators in the Java Collection Class library are conceptually important differences from those in other class libraries. C + + iterators are modeled on an array index. Given such an iterator, you can see the element at the specified position, just as you know the array index I can see the element a[i]. You can move the iterator forward one position without finding the element. This is the same as no need to perform a lookup operation to move the array index forward through i++. However, Java iterators do not do so. Find operations and location changes are tightly linked. The only way to find an element is to call next, while the position of the iterator moves forward as the lookup operation is performed.
That is, you can consider an iterator as a position that is between two elements. The next action will change the position. But when you call next, the iterator crosses the next element and returns a reference to the element that you just crossed.
The Remove method of the iterator interface is used to remove the element that was last called when the next method returns. That is, the remove operation has a dependency on the next operation, and if calling the Remove method without calling the next method is illegal, a IllegalStateException exception is thrown. The following is the first element in the Delete collection:
Iterator<string> it=c.iterator (); It.next (); It.remove ();
If you delete two adjacent elements, the following method is incorrect:
It.remove (); It.remove ();
You must first call the next method over the element you want to delete:
It.remove (); It.next (); It.remove ();
There is a less appropriate metaphor for the iterator to be a cursor:
Collection<string> c=arraylist<> (); C.add ("a"); C.add ("B"); C.add ("C");iterator<string> it= C.iterator ();
At this point, the position of the iterator is as follows:
| A b C
When the next method is called, the cursor moves back and then returns the element that was just crossed:
It.next ();
At this point, the position of the iterator is as follows:
A | A
and returns element A.
If you want to delete an element, the deletion behaves like a back key (Backspace), deleting the element after the cursor (to the right):
It.remove ();
At this point, the position of the iterator is as follows:
| A
Unlike the back key, if there is an element behind the iterator, it cannot be deleted without invoking the next method.
Because both the collection interface and the iterator interface are generic interfaces, you can write a practical way to manipulate any collection type. In fact, there are many methods in the collection interface:
Public interface Java.util.collection<e> extends java.lang.iterable<e> {public abstract int size (); Public abstract Boolean isEmpty (); Public abstract Boolean contains (Java.lang.Object); Public abstract java.util.iterator<e> Iterator (); Public abstract java.lang.object[] ToArray (); Public abstract <T> t[] ToArray (t[]); Public abstract Boolean Add (E); Public abstract Boolean remove (Java.lang.Object); Public abstract Boolean Containsall (java.util.collection<?>); Public abstract Boolean AddAll (java.util.collection<? extends e>); Public abstract Boolean RemoveAll (java.util.collection<?>); public boolean removeif (JAVA.UTIL.FUNCTION.PREDICATE<? super e>); Public abstract Boolean Retainall (java.util.collection<?>); public abstract void Clear (); Public abstract Boolean equals (Java.lang.Object); public abstract int hashcode (); Public java.util.spliterator<e> spliterator (); Public java.util.stream.stream<e> StreAM (); Public java.util.stream.stream<e> Parallelstream ();}There are many ways of meaning are clear, here do not do too much explanation.
Of course, it would be annoying to implement these routine methods for every class that implements the collection interface. To make it easier for the implementation to implement this interface, the Java class Library provides a abstractcollection class that provides a number of routine methods in this class, so that A specific collection class can extend the Abstractcollection class without having to implement all the routine methods, and can overwrite the method inside.
4 interfaces in the Java class Library
All the interfaces in the Java class Library are given:
Of these, collection and map are the two main interfaces of the collection framework, and all of the collection classes implement one of the two interfaces. The iterator interface and the Listiterator interface are iterator interfaces, and the Listiterator interface provides a richer operation, which is described in the list. The Randomaccess interface is a label interface, which means that there is no method for this interface, but you can label a class with this interface, and then check whether a class supports random access.
In a subsequent introduction, the methods and use of these interfaces are described in detail.
5 classes in the Java class Library
Here are all the implementation classes in the Java class Library:
Where the red color is the abstract class. Can be clearly divided into two parts, a set (Collection), a map (map).
These are commonly used classes, plus some specialized classes, such as: Enumset, Linkedhashset, Enummap, Linkedhashmap, Identityhashmap, and Weakhashmap, altogether 14 classes, with the following features:
specific collections in the Java library
| Collection type |
Describe |
| ArrayList |
An index sequence that can dynamically grow and scale |
| LinkedList |
An ordered sequence of efficient insert and delete operations at any location |
| Arraydeque |
A double-ended queue implemented with a loop array |
| HashSet |
An unordered collection with no repeating elements |
| TreeSet |
An ordered set |
| Enumset |
A set containing the value of an enumeration type |
| Linkedhashset |
A set of elements that can remember the insertion order of an element |
| Priorityqueue |
A collection that allows for efficient deletion of the smallest element |
| HashMap |
A data structure for storing key/value associations |
| TreeMap |
A mapping table with ordered order of key values |
| Enummap |
A mapping table with key values that are enumerated types |
| Linkedhashmap |
A mapping table that remembers the order in which key-value items are added |
| Weakhashmap |
A mapping table that can be reclaimed by the garbage collector when its value is useless |
| Identityhashmap |
A mapping table that uses = = rather than equals to compare key values |
For ordered unordered, elements can be duplicated and elements are not repeatable, the characteristics are summarized as follows, note that for map, the value of the key is to be repeatable:
6 more
In the post-analysis, these specific classes and collections are presented:
2. Java Collection (ii): List listing
3. Java Collection (iii): Set set
4. Java Collection (iv): queue queues
5. Java Collection (V): Dedicated set and dedicated map
6. Java Collection (vi): Java Collection framework
7. Java Collection (vii): Algorithms and Legacy classes in Java collections
Java Collection (i): Java Collections Overview