Introduction to Java (iv): Carding of container relationships (--collection)

Source: Internet
Author: User
Tags throw exception

Directory

I. Collection and sub-class/interface container inheritance relationship

Second, List

2.1 ArrayList

Discussion on the 2.1.1 serialization

2.1.2 Deleting elements

2.1.3 Resizing

2.2 Vector and Stack (not recommended for continued use)

2.3 Abstract class Abstractsequentiallist

Third, Set

3.1 HashSet and Linkedhashset

3.2 TreeSet

Iv. Queue

4.1 Priorityqueue

4.2 LinkedList

V. Some trivial topics

5.1 Thread Safety

5.2 Clone ()

5.3 foreach

5.4 Null Object

The container in Java.util is also known as the Java Collections Framework. Although called a framework, its main purpose is to provide a set of interfaces that are as simple as possible and as efficient as possible for developers to choose from, rather than repeating, their own implementations. Containers can be divided into two main categories by interface: collection and map. This article is mainly concerned about collection, the map of this block will also be studied.

I. Collection and sub-class/interface container inheritance relationship

Start with the collection, please. Can be seen:

The 1.Collection interface is not a root interface, its super interface is iterator, and it needs to provide its ability to traverse, remove elements (optional operations).

The 2.Collection interface defines the basic container operation method.

Besides

1.remove () and contains () determine whether the elements are equal in the same basis.

For remove (Object o), if the element contained in collection E is satisfied (O==null. E==null:o.equals (e)), one of them is removed;

For contains (Object O), returns True if collection contains at least one or more element E, which satisfies (O==null. E==null:o.equals (e)).

2.AbstractCollection Abstract class implements a part of the collection interface method, mainly based on iterator implementations, such as remove (), ToArray (), and size (), which is implemented using its own property size. If you read the source code, you can see that although abstractcollection uses add () to implement AddAll (), the implementation of the Add () itself is a direct throw unsupportedoperationexception exception. The fact that add () is an "optional operation" is intended to delay the implementation until it is needed.

Second, List

After understanding the general collection, next, look at the three categories of collection:list, Set, Queue. First, start with list. The elements in the list are ordered so that we can sequentially access the elements in the list and access the elements at the specified location. For the need to "iterate through the access element sequentially", the iterator of the list's super interface can be done, which is also the implementation in the abstractlist of the abstract class, while accessing the elements of a particular location (that is, access by index), The addition and deletion of elements involves the connection of elements in the list, and is not available in abstractlist.

2.1 ArrayList

ArrayList is the most common implementation of the list, which wraps an array for storing elements, and uses the Size property to identify the number of elements in the container, rather than the size of the wrapped array. If the array is understood, it is easy to understand how the elements of the ArrayList are arranged, how the elements of each array are randomly accessed (through the index), and how the elements jump between them (the index increases or decreases). Read the source code can be found that this array is decorated with the transient keyword, indicating that it will not be serialized. Of course, ArrayList elements will eventually be serialized, otherwise, one of the most commonly used list, can not be persisted, not network transmission, it is unthinkable. When serializing/deserializing, ArrayList's WriteObject ()/readobject () method is called to write the element in the ArrayList (that is, the element corresponding to the 0...size-1 subscript) to the stream/read out from the stream. The advantage of this is that it saves/transmits only elements that are meaningful, saving the overhead of storage, transport, and processing.

discussion on the 2.1.1 serialization

When it comes to serialization, there is a question of how ArrayList's WriteObject ()/readobject () is called. They do not belong to any interface of ArrayList, or even serializabe! In fact, serialization is when the ObjectOutputStream object calls its own WriteObject () method, by which it examines the incoming parameter through reflection-that is, the object to be serialized-whether there is a writeobject () method, and makes the call, which is independent of the interface, It's really weird (you can refer to the Java Programming Idea • Fourth edition (Chinese), page No. 581).

2.1.2 Deleting elements

ArrayList when deleting an element, not only will the other element be moved forward to occupy the removed element and reduce the size, the (size-1) position is set to NULL for elements of the original position, such as the (size-1) position before the element is moved to the (size-2) bit. This allows the garbage collection mechanism to work. The use of this data is common in Java, as is the case with stacks implemented with vectors. In the C language, a stack implemented using an array can only modify the array subscript of the current stack after the pop () and not clean it.

2.1.3 Resizing

Use the Arrays.copyof () method to make an array adjustment.

2.2 vector and stack (not recommended for continued use)

Although the vector has been modified, it is only intended to be compatible with JAVA2 code before it is recommended to continue.

Java1.6 source code, and ArrayList similar, Vector bottom is also an array, but this array is not transient decorated, its serialization is much less effective.

Instead of wrapping a vector, the stack is implemented by inheriting vectors. This is not a good design, and if you want to use stack behavior, you should use LinkedList. Java1.6 source code, the stack every time the expansion requires a new array and copy, the efficiency is not good.

The reason for the misuse of these two containers in the new code is probably the previously used STL vector and Stack in C + +. When I first approached Java, I thought the two classes would have a similar position in Java, like C + +.

2.3 Abstract class Abstractsequentiallist

A list that satisfies the continuous access data store rather than the random access requirement requires an iterator that uses the abstract method Listiterator () for the operation of the specified index element. Its only implementation is linkedlist, and the discussion of it is placed in this part of the queue.

Third, Set

The set interface mimics the set of mathematical concepts, and each element does not require repetition. In addition to this, almost the same as the collection itself.

The set interface has a direct sub-interface SortedSet, which requires that all elements in the set are ordered. and "ordered" to access all the elements sequentially through the Iterable interface, this "ordered" requirement set includes a comparator that can determine the greater than, less than, or equal to the two elements of a relationship. In addition, the interface provides access to the first element, access to the last element, and access to elements within a certain range of methods. The SortedSet sub-interface Navigableset further expands on this series of methods, providing methods such as returning the first element greater than/less than element E.

Because the operation of set and the implementation of the underlying is very strong, the method implemented in Abstractset is limited, only equals (), Hashcode (), RemoveAll () are implemented in Java1.6.

3.1 hashset and Linkedhashset

HashSet's name includes "Hash" because its underlying is implemented with HashMap. Map has a feature that each key is unique, which is very similar to the set element. The operation of the HashSet element E is actually the corresponding <E,PRESENT> in the hashmap of its wrapper, where PRESENT is a private static final object. Therefore, the principle of hashset, put to hashmap that piece to study.

HashSet has a very special method of structuring: HashSet (int initialcapacity, float loadfactor, Boolean dummy). The only effect of the third parameter of this method is to distinguish it from the construction of the other two parameters. Using this construction method, the HashMap subclass Linkedhashmap is used at the bottom. Linkedhashset, however, uses this construction method to create and encapsulate a linkedhashmap rather than a generic hashmap in-house.

  If first has HashSet, after has HashMap, uses HashSet realizes HashMap, whether is a good idea? This is also studied at the HashMap place.

The HashMap of the HashSet packaging is also decorated with transient keywords, using the same serialization strategy as ArrayList.

3.2 TreeSet

TreeSet is an implementation of SortedSet, and also the implementation of its sub-interface Navigableset.

Similar to Hashset/linkedhashset, the TreeSet layer encapsulates a navigablemap, using transient adornments as well as serialization strategies.

Iv. Queue

There are two differences between the queue and list: The former has the concept of "team head", taking elements, removing elements, all operations on the "Team head" (usually but not always FIFO, that is, first-out), the latter only need to ensure at the end of the insertion, the former on the elements of some of the same operation provides two methods, Throws the exception/return special value--add ()/offer (), remove ()/poll (), Element ()/peek () in a particular case. It is not difficult to think that in the so-called two methods, the method of throwing the anomaly can be achieved by wrapping the method of not throwing the exception, which is what Abstractqueue did.

The Deque interface inherits the queue, but it has no relationship with Abstractqueue. Deque also provides an insert and delete operation at the head and tail of the team.

4.1 priorityqueue

The priorityqueue is used to hold the elements that contain precedence, and the inserted objects must be comparable. An array is also encapsulated inside the class. Unlike the abstract parent class Abstractqueue, Priorityqueue's offer () method throws a null pointer exception when inserting NULL--null is not a priority in the usual sense of comparison with other elements; In addition, the Add () method is directly wrapping the offer () , there is no additional behavior.

Because its internal data structure is the reason of the array, many operations need to first convert the elements through indexof () to the corresponding array subscript, and then further operations, such as remove (), Removeeq (), contains () and so on. In fact, this array to maintain the priority queue way, is the use of heap (heap), the specific can refer to any of the algorithm books, such as "Introduction to the algorithm," and so on, here does not expand the explanation. is related to the properties of the heap, which must be traversed from beginning to the other when looking for the specified element, rather than using a binary lookup.

4.2 LinkedList

Interestingly, LinkedList is both a list and a queue (Deque) because it is bidirectional, and the inner element (Entry) retains a reference to the previous and next elements. You can get a trailing reference by using the header of the header and taking its previous. With this transformation, it is easy to implement the behavior required by deque. It is therefore possible to support the behavior of stacks, which are inherently push () and Pop () methods. In short, it is a doubly linked list in Java, which supports operations like normal doubly linked lists.

Unlike arrays, when a particular element is looked up according to the subscript, it can only be traversed to obtain it, and thus is less efficient than ArrayList at random access. Nevertheless, the author has made the best use of LinkedList's features to optimize the site, minimizing the number of visits:

    PrivateEntry<e> Entry (intindex) {        if(Index < 0 | | | Index >=size)Throw NewIndexoutofboundsexception ("Index:" +index+ ", Size:" +size); Entry<E> E =header; if(Index < (size >> 1)) {             for(inti = 0; I <= index; i++) e=E.next; } Else {             for(inti = size; i > Index; i--) e=e.previous; }        returne; }
v. Some trivial topics5.1 Thread Safety

ArrayList, Hashset/linkedhashset, Priorityqueue, LinkedList are thread insecure and can be resolved using the Synchronized keyword, or similar to the following:

List List = Collections.synchronizedlist (new ArrayList (...));
5.2 Clone ()

Clone () of ArrayList, LinkedList, Hashmap/linkedhashmap, TreeSet is a shallow copy, and the element's reference is the same as before the copy, and the Priorityqueue clone () inherits from object.

5.3 foreach

In for (Element e:collection):

Collection = = NULL, direct throw exception;

The contents of the container are empty, that is just being new out, there is nothing inside, skip the loop directly;

Null is placed in the container (if allowed), the null is fetched and assigned to E, and the statement in the loop is executed.

5.4 Null Object

List can be placed infinitely more, set can only be placed one. Enumset, Priorityqueue cannot be null. This null is also in the count. So put it in. Null is required to be removed with foreach.

Introduction to Java (iv): Carding of container relationships (--collection)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.