Underlying source code parsing for Java generics and underlying source code for java generics

Source: Internet
Author: User

Underlying source code parsing for Java generics and underlying source code for java generics

Statement:The following source code is based on JDK1.8 _ 112.

1. ArrayList source code parsing

<1. The collection still stores object references rather than the object itself, and cannot place native data types. We need to use native data-type packaging classes to add them to the collection.

<2. All objects are placed in the collection. Therefore, the retrieved Object type must be converted to the desired type, that is, the type of the Object to be placed.

1 ArrayList list = new ArrayList();2 list.add(new Integer(4)); list.add("abc");3 System.out.println((Integer)list.get(0));4 System.out.println((String)list.get(1));

<3. ArrayList usesArrayWhen ArrayList Object is generated using a constructor without parameters, an array of the Object type with a length of 10 is actually generated at the underlying layer.

The differences between JDK versions need to be distinguished here. jdk1.6 or the underlying layer used the basic multiplication operation during resizing: 3/2 * oldCapacity + 1; after jdk1.7, the bottom layer adopts the displacement operation during the expansion, and does not add 1 more operation: oldCapacity + (oldCapacity> 1) (I guess it is best to fully consider improving the computing performance)

<4. The real expansion is to copy the content of the original array to the new array, and the subsequent content will be placed in the new array.

Here we post the jdk1.8 resizing code:

private void grow(int minCapacity) {    // overflow-conscious code    int oldCapacity = elementData.length;    int newCapacity = oldCapacity + (oldCapacity >> 1);    if (newCapacity - minCapacity < 0)        newCapacity = minCapacity;    if (newCapacity - MAX_ARRAY_SIZE > 0)        newCapacity = hugeCapacity(minCapacity);    // minCapacity is usually close to size, so this is a win:    elementData = Arrays.copyOf(elementData, newCapacity);}

ElementData is defined as follows:

transient Object[] elementData; // non-private to simplify nested class access

<5. boolean add (E) and void add (int, E) use different underlying methods

Adding an object directly to the set adds the object to the end of the data by default, which is also the fastest, that is, elementData [size ++] = e; --> assign an element to the last digit in the array order.

The add method for specifying the insert position needs to use the System. arraycopy method to assign values to the array operation from the specified position + 1, and then assign values to the corresponding elements. The source code is as follows:

1 public void add(int index, E element) {2     rangeCheckForAdd(index);3 4     ensureCapacityInternal(size + 1);  // Increments modCount!!
5   //public static native void arraycopy(Object src, int srcPos, Object dest, int destPos, int length);6 System.arraycopy(elementData, index, elementData, index + 1, size - index);7 elementData[index] = element;8 size++;9 }

Set (int, E), remove (int), and remove (Object) are similar actions, that is, how the ArrayList underlying layer is operated by the array.

2. parse the mongolist source code

The underlying source code of the shortlist isTwo-way linked listThe specific two-way list Initialization is defined as follows:

 1 private static class Node<E> { 2     E item; 3     Node<E> next; 4     Node<E> prev; 5  6     Node(Node<E> prev, E element, Node<E> next) { 7         this.item = element; 8         this.next = next; 9         this.prev = prev;10     }11 }

What is a two-way list? A one-way linked list can find the next pointing element through the next link. A two-way linked list can either find the next pointing element through the next link or find the previous element through the precursor.

Then the remaining add, remove, and other methods are just to change the corresponding point. This implementation is very simple. Here we will not detail it, but we will understand it after looking at the source code.

3. HashSet source code parsing

First, let's take a look at the corresponding source code for the non-argument constructor of HashSet that we often use:

/** * Constructs a new, empty set; the backing HashMap instance has * default initial capacity (16) and load factor (0.75). */public HashSet() {    map = new HashMap<>();}

From the source code above, we can see that the bottom layer of the HashSet is implemented using HashMap, and the default initial length of the corresponding HashMap is 16, and the corresponding load factor is 0.75. Let's look at the source code of common methods such as add (), remove (), and iterator:

public boolean add(E e) {    return map.put(e, PRESENT)==null;}public boolean remove(Object o) {    return map.remove(o)==PRESENT;}public Iterator<E> iterator() {    return map.keySet().iterator();}

The PRESENT constant is defined as follows:

// Dummy value to associate with an Object in the backing Mapprivate static final Object PRESENT = new Object();

From the source code above, it is found that when an object is added to the Set using the add () method, the object is actually the key of the Map object maintained by the underlying layer, while value is the same Object (this Object cannot be used)

Now that HashSet directly uses HashMap for maintenance at the underlying layer, we need to analyze the underlying source code of HashMap.

4. HashMap source code parsing

First, let's take a look at the corresponding source code for the non-argument constructor of HashMap that we often use:

/** * Constructs an empty HashMap with the default initial capacity * (16) and the default load factor (0.75). */public HashMap() {    this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted}

 

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.