Java Collection class: AbstractCollection source code parsing,

Source: Internet
Author: User

Java Collection class: AbstractCollection source code parsing,

1. Collection Interface

From the article "Java Set: Overall Structure", we know that all lists and sets inherit from the Collection interface. This interface class provides the most basic method of the Set, although the List interface and Set have some unique methods, the basic operations are similar. Let's take a look at the methods provided by the Collection interface:

  Ii. source code parsing of AbstractCollection

Package java. util; public abstract class AbstractCollection <E> implements Collection <E> {protected AbstractCollection () {} public abstract Iterator <E> iterator (); public abstract int size (); // determine whether data in the set is public boolean isEmpty () {return size () = 0;}/*** determine whether to include the specified Element * (1) if the parameter is null, find the element whose value is null. If the parameter exists, true is returned. Otherwise, false is returned. * (2) if the parameter is not null, The equals method is used to search for elements equal to the parameter. If the parameter exists, true is returned. Otherwise, false is returned. * Note: null must be processed separately. Otherwise, null is returned. equals returns a null pointer exception */public boolean contains (Object o) {Iterator <E> it = iterator (); if (o = null) {while (it. hasNext () if (it. next () = null) return true;} else {while (it. hasNext () if (o. equals (it. next () return true;} return false;}/*** function: convert a set element to an array * Implementation: * (1) Create an array, the size is the number of elements in the Set * (2) use the iterator to traverse the set and copy the elements in the current set to the array (copy reference) * (3) if the number of elements in the set is less than expected, Arrays is called. the copyOf () method copies the elements of the array to the new number. Group, and return the new array, Arrays. the source code of copyOf will be analyzed in subsequent articles. * (4) if the set contains more elements than expected, call the finishToArray method to generate a new array and return a new array. Otherwise, return (1) array created in */public Object [] toArray () {Object [] r = new Object [size ()]; Iterator <E> it = iterator (); for (int I = 0; I <r. length; I ++) {if (! It. hasNext () // fewer elements than expected return Arrays. copyOf (r, I); r [I] = it. next ();} return it. hasNext ()? FinishToArray (r, it): r;}/*** function: return an array of the specified type through generic constraints * Implementation: * (1) if the length of the input array is greater than or equal to the length of the Set, copy the elements of the current set to the input array * (2) if the length of the input array is less than the size of the set, a new array will be created to store the collection elements */public <T> T [] toArray (T [] a) {// Estimate size of array; be prepared to see more or fewer elements int size = size (); T [] r =. length> = size? A: (T []) java. lang. reflect. array. newInstance (. getClass (). getComponentType (), size); Iterator <E> it = iterator (); for (int I = 0; I <r. length; I ++) {// the size of the Set element is smaller than the length of the array if (! It. hasNext () {// fewer elements than expected if (a = r) {// if the array is an array in the parameter, set the remaining values to null r [I] = null; // null-terminate} else if (. length <I) {// if the length of the input array is smaller than the length of the Set, Arrays is used. copyOf copies the elements in the previous array to the return Arrays in the new array. copyOf (r, I);} else {// if the length of the input array is greater than that of the Set, multiple elements are set to null System. arraycopy (r, 0, a, 0, I); if (. length> I) {a [I] = null;} return a;} r [I] = (T) it. next ();} // more elements than expected/ /Return it. hasNext ()? FinishToArray (r, it): r;} private static final int MAX_ARRAY_SIZE = Integer. MAX_VALUE-8;/*** function: array expansion * (1) when the array index points to the last element + 1, expand the array: Create a longer array, then copy the content of the original array to the new array * (2) resize: cap + cap/2 + 1 * (3) before resizing, you must first determine whether the array length exceeded * Note: The iterator here is passed from the upper-layer method (toArray), and this iterator has executed part of it, instead of the */private static <T> T [] finishToArray (T [] r, Iterator <?> It) {int I = r. length; while (it. hasNext () {int cap = r. length; if (I = cap) {int newCap = cap + (cap> 1) + 1; // overflow-conscious code if (newCap-MAX_ARRAY_SIZE> 0) newCap = hugeCapacity (cap + 1); r = Arrays. copyOf (r, newCap);} r [I ++] = (T) it. next ();} // trim if overallocated return (I = r. length )? R: Arrays. copyOf (r, I);}/*** determines whether the array capacity overflows. The maximum value is the maximum value of Integer Data */private static int hugeCapacity (int minCapacity) {if (minCapacity <0) // overflow throw new OutOfMemoryError ("Required array size too large"); return (minCapacity> MAX_ARRAY_SIZE )? Integer. MAX_VALUE: MAX_ARRAY_SIZE;}/*** not implemented */public boolean add (E e) {throw new UnsupportedOperationException ();}/*** function: remove the specified Element * (1) if the parameter is null, find the first element with the null value and delete it. true is returned. If the element without null exists, false is returned. * (2) if the parameter is not null, find the first element equal to the parameter based on the equals method, delete it, and return true. If no element is found, false is returned. */Public boolean remove (Object o) {Iterator <E> it = iterator (); if (o = null) {while (it. hasNext () {if (it. next () = null) {it. remove (); return true ;}} else {while (it. hasNext () {if (o. equals (it. next () {it. remove (); return true ;}}return false;}/*** traverses the parameter set to determine whether the elements in the parameter set are in the current set. * if one does not exist, returns false * if all the elements in the parameter set are in the current set, returns true */public boolean containsAll (Collection <?> C) {for (Object e: c) if (! Contains (e) return false; return true;}/*** traverses the parameter set and sequentially adds the elements in the parameter set to the current set */public boolean addAll (Collection <? Extends E> c) {boolean modified = false; for (E: c) if (add (e) modified = true; return modified;}/*** function: remove the element of the parameter set * (1) Get the iterator of the current set for traversal * (2) if the element of the current set is included in the parameter set, delete the elements in the current set * Note: As long as any element in the parameter set is in the current element, true is returned, indicating that the current set has sent changes; otherwise, false is returned. */Public boolean removeAll (Collection <?> C) {boolean modified = false; Iterator <?> It = iterator (); while (it. hasNext () {if (c. contains (it. next () {it. remove (); modified = true;} return modified;}/*** function: intersection of the parameter set and the current set * (1) get the iterator of the current set for traversal * (2) if the element in the current set is not in the parameter set, remove it. * Note: if the current set is a subset of the parameter set, false is returned, indicating that the current set has not been changed; otherwise, true is returned. */Public boolean retainAll (Collection <?> C) {boolean modified = false; Iterator <E> it = iterator (); while (it. hasNext () {if (! C. contains (it. next () {it. remove (); modified = true;} return modified;} // delete all elements public void clear () {Iterator <E> it = iterator (); while (it. hasNext () {it. next (); it. remove () ;}} public String toString () {Iterator <E> it = iterator (); if (! It. hasNext () return "[]"; StringBuilder sb = new StringBuilder (); sb. append ('['); for (;) {E = it. next (); sb. append (e = this? "(This Collection)": e); if (! It. hasNext () return sb. append (']'). toString (); sb. append (','). append ('');}}}

In general, the source code of AbstractCollection is easier to understand, especially the operations such as adding, deleting, and querying collections. The complicated operation is about converting a set to an array. I am not particularly familiar with the following points:

(1) MAX_ARRAY_SIZE = Integer. MAX_VALUE-8. Why is the maximum length reduced by 8? According to the official explanation:

/**

* The maximum size of array to allocate.

* Some VMs reserve some header words in an array.

* Attempts to allocate larger arrays may result in

* OutOfMemoryError: Requested array size exceeds VM limit

*/

Some virtual machines implement this. the header of the array object occupies these 8 bytes.

(2) Why is the length longer or shorter than size () when converting to an array? This is because the concurrency is taken into account. Of course, the Mechanism in the concurrency environment is not necessarily feasible. For example, this method is rewritten in ArrayList and the size () if it is inconsistent with hasNext, an error is reported directly. However, in some scenarios, we can use this method to maintain weak consistency, which will be explained later.

(3) When copying an array, two methods are used: Arrays. copyOf, the other is System. the differences between arraycopy (r, 0, a, 0, I) methods will be discussed in subsequent articles.

Iii. Summary

This article mainly analyzes the source code of the AbstractCollection class. Many implementation classes will overwrite the implemented methods in AbstractCollection. However, after you understand the source code of AbstractCollection, you can look at the implementation of its subclass to better understand the design reasons behind its source code implementation. In fact, many source codes are not hard to understand, what is hard to understand lies in the design ideas and causes behind it. This is what we look at the source code and what we really want to learn.

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.