A thorough understanding of the container class (2) ------- begin actcollection

Source: Internet
Author: User

A thorough understanding of the container class (2) ------- begin actcollection
Understanding of AbstractCollection

AbstractCollection is an abstract Implementation of the Collection interface. Implemented some Colleciton and added several new methods.

 

Push before source code

Before reading the source code of AbstractCollection, let's take a look at some other source codes used in AbstractCollection.

  • System. arraycopy (Object src, int srcPos, Object dest, int destPos, int length );
  • Arrays. CopyOf (T [] original, int newLength)

1. System. arraycopy is the Native method, which is a local java method and written in other languages. Therefore, we cannot see the underlying code. However, the native method is generally more efficient than writing by yourself. This method is used to copy (srcPos to srcPos + length-1) elements from src to destPos + length-1 in dest.

  System. arraycopy (Object src, int srcPos, Object dest, int destPos, int length );

Src: source indicates the source array.

SrcPos: source position indicates the starting position of the source array.

Dest: destination indicates the target array.

Destpos: destination position starting position of the target array

Length: number of elements copied by length

  Src and dest can be the same Array

 public static native void arraycopy(Object src,  int  srcPos,                                      Object dest, int destPos,                                      int length);

  2.Arrays. CopyOf (T [] original, int newLength)

Arrays. CopyOf (U [] original, int newLength, Class <? Extends T []> newType)

This method returns a T [].

   Original: the copied Array

NewLength: length of the returned new array

NewType: the type of the returned array (for example, the String [] array or the Integer [] array). Note that the parent class of all arrays is Object [].

@ SuppressWarnings ("unchecked") public static <T> T [] copyOf (T [] original, int newLength) {return (T []) copyOf (original, newLength, original. getClass ();} public static <T, U> T [] copyOf (U [] original, int newLength, Class <? Extends T []> newType ){
@ SuppressWarnings ("unchecked ")
     // Create an Object array if the type is the same as that of Object []. class. Otherwise, create an array of a specific type.T [] copy = (Object) newType = (Object) Object []. class )? (T []) new Object [newLength]: (T []) Array. newInstance (newType. getComponentType (), newLength );

     // Move the source array to the target arraySystem. arraycopy (original, 0, copy, 0, Math. min (original. length, newLength); return copy ;}
Source code analysis 1. Class declaration, implementing the Collection Interface
public abstract class AbstractCollection<E> implements Collection<E> {}

 2. constructor method .... ● ○ ........... ● ○ ........... ● ○ ........... gorgeous split line

  //Protected ModificationThe description is only visible to the subclass or the same package.

Protected AbstractCollection (){}

3. abstract method .... ● ○ ........... ● ○ ........... ● ○ ........... gorgeous split line

Public abstract Iterator <E> iterator (); the abstract method is not implemented.

Public abstract int size ();Abstract MethodNot Implemented

4. Determine if it is null.... ● ○ ........... ● ○ ........... ● ○ ........... Gorgeous split line

// Determine whether the container is empty by determining whether the size is equal to 0

 Public boolean isEmpty (){
Return size () = 0;
}

5. determine whether an element is included● ○ ........... ● ○ ........... ● ○ ........... Gorgeous split line

Public boolean contains (Object o ){
Iterator <E> it = iterator ();

// If the input value is null, The iterator is used to compare whether the input value is null. If the input value is null, true is returned.
If (o = null ){
While (it. hasNext ())
If (it. next () = null)
Return true;

    // If the input is not null, It is compared by the iterator using the equals method. true is returned.
} Else {
While (it. hasNext ())
If (o. equals (it. next ()))
Return true;
}

// Returns false if no equality exists.
Return false;
}

  6. Return an Object array through the container iterator... ○ ......... ○...

Public Object [] toArray (){
Object [] r = new Object [size ()];
Iterator <E> it = iterator ();
For (int I = 0; I <r. length; I ++ ){

      // If fewer elements than expected is less than expectedArrays. copyOf generates Arrays of objects with exactly the same number
If (! It. hasNext ())
Return Arrays. copyOf (r, I );

// Assign the reference of the element in the iterator to the array
R [I] = it. next ();
}

  // If the number of iterator elements is greater than the size, returnFinishToArray (r, it). Otherwise, the object is directly returned.
Return it. hasNext ()? FinishToArray (r, it): r;
}

7. add all the remaining elements in the iterator to the array.... ○ ......... ○...

// The maximum array capacity

Private static final int MAX_ARRAY_SIZE = Integer. MAX_VALUE-8;MAX_ARRAY_SIZE;

@ SuppressWarnings ("unchecked ")
Private static <T> T [] finishToArray (T [] r, Iterator <?> It ){
Int I = r. length;
While (it. hasNext ()){
Int cap = r. length;

// If the capacity is full, scale up.
If (I = cap ){
Int newCap = cap + (cap> 1) + 1;

// Automatically detects whether the capacity exceeds the size of the array allowed by the virtual machine,
If (newCap-MAX_ARRAY_SIZE> 0)
NewCap = hugeCapacity (cap + 1 );

// R is assigned to a new object array object. The object size is newCap (new Capacity)
R = Arrays. copyOf (r, newCap );
}

// I auto-increment and assign a new element
R [I ++] = (T) it. next ();
}
// Trim if overallocated if the array capacity is sufficient, trim the array into a better capacity.
Return (I = r. length )? R: Arrays. copyOf (r, I );
}

// Re-assign a size becauseCap + (cap> 1) + 1 may exceed the maximum value of int, or exceed the maximum value of array Length

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;
}

8. The add method is not supported.... ○...

Public boolean add (E e ){
Throw new UnsupportedOperationException ();
}

9 remove an element... ○... Gorgeous split line

Public boolean remove (Object o ){
Iterator <E> it = iterator ();

// If it is null, true is directly returned if it is null.
If (o = null ){
While (it. hasNext ()){
If (it. next () = null ){
It. remove ();
Return true;
}
}
} Else {

    // Traverse iterator,If an object is equal, return
While (it. hasNext ()){
If (o. equals (it. next ())){

// The iterator is used to eliminate objects (the iterator does not necessarily implement elimination. For example, an UnsupportedOperationException () may be thrown when the iterator is eliminated ())
It. remove ();
Return true;
}
}
}
Return false;
}

10. Whether it contains all the elements in the input parameters... ● ○ ...... ● ○...

Public boolean containsAll (Collection <?> C ){
For (Object e: c)

    // If one does not contain any content, false is returned directly.
If (! Contains (e ))
Return false;
Return true;
}

11. Add all elements to the container.... ○...

Public boolean addAll (Collection <? Extends E> c ){

  // Modified indicates whether the element has been modified.
Boolean modified = false;

    // Traverse the parameter container and add the method to the container
For (E: c)
If (add (e ))
Modified = true;
Return modified;
}

12. Remove all.. ● ○ ........... ● ○ ........... ● ○ ........... Gorgeous split line

Public boolean removeAll (Collection <?> C ){

// If C is null, an exception is thrown.
Objects. requireNonNull (c );
Boolean modified = false;
Iterator <?> It = iterator ();
While (it. hasNext ()){

    // Traverse the c container. If the element is included, remove the element.
If (c. contains (it. next ())){
It. remove ();
Modified = true;
}
}
Return modified;
}

13. Remove all elements.. ● ○ ........... ● ○ ........... ● ○ ........... Gorgeous split line

Public void clear (){
Iterator <E> it = iterator ();
While (it. hasNext ()){
It. next ();

// The iterator removes elements.
It. remove ();
}
}

14. toString Method. ● ○ ........... ● ○ ........... ● ○ ........... Gorgeous split line

Public String toString (){

  // If no element is included, return []
Iterator <E> it = iterator ();
If (! It. hasNext ())
Return "[]";

StringBuilder sb = new StringBuilder ();
Sb. append ('[');
For (;;){
E e = it. next ();

// E = this is used to prevent endless Loops
Sb. append (e = this? "(This Collection)": e );
If (! It. hasNext ())
Return sb. append (']'). toString ();
Sb. append (','). append ('');
}
}

Summary: AbstractCollection is only a template used by other classes. To become a working container, many methods and stored element objects are required.

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.