Java basics of Perplexed Java-Set and List

Source: Internet
Author: User

From learning Java to now also has a small 10 years, work has been in use but the theoretical knowledge is always forgotten, with a lot of learning a lot but the system. People are almost 30, had been?

Recently saw a blogger in Csdn wrote a good Java series blog, I this person is more lazy estimated from 0 to write down, so stand on the shoulders of "giants" to start their own notes, hoping to compare the Java knowledge of the system to comb a bit.
This blog a lot of reference to the beauty of Java [from rookie to master evolution] of the collection class, because it has been written very well, this blog will be added to some of the details.

The collection is the longest, most commonly used collection class in our development:

    1. Implement collection interface: Set, list and so on;
    2. Implementation of the Map interface: hashmap,hashtable, etc.



(from the user's summary)

This is an important part of the implementation of Set and list source code. Because the beauty of Java [from rookie to master evolution] of the collection class has been said very good, I here only highlight the focus on some knowledge points.

Set parsing

The members in Set are not repeatable, unordered (but TreeSet is an exception is ordered).
Say more, why is set not necessary? Take HashSet as an example, let's take a look at why we can not repeat the following questions to solve the problem.

take HashSet as an example , the source code of theAdd method

    publicbooleanadd(E e) {        return map.put(e, PRESENT)==null;    }

What is the main view of E,e? is the element that is added to the set. is the element to be added in the form of a map key, the underlying storage or map . The present is dine.

Let's look at the put method in more detail:

   PublicVput(K key, V value) {if(Key = =NULL)returnPutfornullkey (value);inthash = hash (Key.hashcode ());//----------1----------        inti = indexfor (hash, table.length);//-----------2---------         for(entry<k,v> e = table[i]; E! =NULL; E = e.next) {//-----------3-------Object K;if(E.hash = = Hash && (k = e.key) = = Key | | key.equals (k)))                   {V oldValue = E.value;                   E.value = value; E.recordaccess ( This);returnOldValue; }           }//------------------4--------------------modcount++; AddEntry (hash, key, value, I);return NULL; }

When adding elements to HashMap, first calculate the hashcode value of the element, and then calculate the value of the hashcode according to the code at 1, and then calculate the storage location of the element according to the code at 2, and if the position is empty, add the element; if it is not, then look at the 3-4 code , the elements on the chain that are indexed as I are traversed, and if key repeats, the OldValue value is replaced and returned.

When traversing :
Because E is placed in the key of the map, the bottom layer can only be confirmed by the hashcode of E (the logic of the position is: (the hashcode of the Element)% (the size of the HashMap collection) +1), the hashcode of each e is not sequential, So there is no guarantee of order when iterator. is the following source code * *

    publiciterator() {           return map.keySet().iterator();        }  

Specific hashmap of the source code will be in the post-blog detailed introduction.

ArrayList parsing

What is ArrayList?
ArrayList is an array-based implementation, and it is a dynamic array whose capacity can grow automatically.

1. ArrayList不是线程安全的,只能用在单线程环境下,多线程环境下可以考虑用Collections.synchronizedList(List l)函数返回一个线程安全的ArrayList类,也可以使用concurrent并发包下的CopyOnWriteArrayList类;2. 实现了Serializable接口,就支持了序列化;3. 实现了RandomAccess接口,支持快速随机访问;4. 实现了Cloneable接口,能被克隆;5. 使用ensureCapacity操作进行容量的自增长。
 //There is such a line in the source code  Public  class ArrayList<e> extends abstractlist<e> Implements List<E;, randomaccess, cloneable, java. io. Serializable ...  Public void ensurecapacity  (int paramint) {     This. Modcount + =1;inti = This. elementdata.length;if(Paramint > i) {object[] Arrayofobject = This. Elementdata;intj = i *3/2+1;if(J < Paramint) J = paramint; This. Elementdata = arrays.copyof ( This. Elementdata, j); }  }

As can be seen from the above code, when the array is expanded, the elements in the old array are re-copied to the new array, each time the capacity of the array increases by approximately 1.5 times times its original capacity . The cost of this kind of operation is very high, so we should try our best to avoid the expansion of the array capacity in actual use. When we can predict the number of elements to be saved, we specify their capacity when constructing ArrayList instances to avoid the occurrence of array expansion. or by calling the Ensurecapacity method to manually increase the capacity of the ArrayList instance, depending on the actual demand. the ensurecapacity (int paramint) method can be used to increase the initialization speed of ArrayList .

Private Properties

Elementdata stores the element within the ArrayList, which represents the number of elements it contains

/*** The array buffer into which the elements of the ArrayList are stored.* The capacity of the ArrayList is the length of this array buffer. Any* empty ArrayList with elementData == EMPTY_ELEMENTDATA will be expanded to* DEFAULT_CAPACITY when the first element is added.*/privatetransientprivateint size;

transient What does that mean?
Ava's serialization provides a mechanism for persisting object instances. When persisting an object, there may be a special object data member, and we do not want to use the serialization mechanism to save it. In order to turn off serialization on a domain of a particular object, you can precede the field with the keyword transient. Refer to Java examples userinfo and testtransient.
The simple understanding is that attributes marked as transient are not saved when the object is serialized.

element Storage

This knowledge point is more important, need to read the source carefully.

//replaces the element at the specified position in this list with the specified element and returns the element that was previously at that location.   PublicESet(intIndex, E Element) {Rangecheck (index);      E OldValue = (e) elementdata[index]; Elementdata[index] = element;returnOldValue; }//Adds the specified element to the end of this list.   Public Boolean Add(e) {ensurecapacity (size +1); elementdata[size++] = e;return true; }//Inserts the specified element into the specified position in this list.  //If there are elements in the current position, move the element that is currently at that position and all subsequent elements (index plus 1) to the right.   Public void Add(intIndex, E Element) {if(Index > Size | | Index <0)Throw NewIndexoutofboundsexception ("Index:"+index+", Size:"+size);//If the array length is insufficient, the expansion will be performed. Ensurecapacity (size+1);//increments modcount!!     //The element with a length of size-index starting at the index position in the Elementdata ,    //Copy to the new Elementdata array starting from the subscript index+1 position.     //The element that is currently at that location and all subsequent elements move right one position. System.arraycopy (Elementdata, index, elementdata, index +1, Size-index);      Elementdata[index] = element;   size++; }//Add all elements in the collection to the end of this list by the order of the elements returned by the specified collection iterator.   Public Boolean AddAll(collection<? extends e> c) {object[] a = C.toarray ();intNumnew = A.length; Ensurecapacity (size + numnew);//increments ModcountSystem.arraycopy (A,0, Elementdata, size, numnew); Size + = Numnew;returnNumnew! =0; }//starts from the specified position and inserts all elements from the specified collection into this list.   Public Boolean AddAll(intindex, COLLECTION&LT;? Extends e> c) {if(Index > Size | | Index <0)Throw NewIndexoutofboundsexception ("Index:"+ Index +", Size:"+ size); Object[] A = C.toarray ();intNumnew = A.length; Ensurecapacity (size + numnew);//increments Modcount    intnummoved = Size-index;if(Nummoved >0) system.arraycopy (elementdata, index, elementdata, index + numnew, nummoved); System.arraycopy (A,0, Elementdata, index, numnew); Size + = Numnew;returnNumnew! =0; }

You see that add (e) calls the Ensurecapacity (size+1) method First, then assigns the index of the element to Elementdata[size], and then the size is self-increment. For example, when first added, size 0,add elementdata[0] is assigned to E, and size is set to 1 (similar to executing the following two statements elementdata[0]=e;size=1). Assigning an element's index to elementdata[size] is not the case that the array is out of bounds? The key here is in Ensurecapacity (size+1).

element Deletion
    publicremove(int index) {        rangeCheck(index);        modCount++;        E oldValue = elementData(index);        int1;        if0)            System.arraycopy(elementData, index+1, elementData, index,                             numMoved);        null// clear to let GC do its work        return oldValue;    }

The simple understanding is:

1. 首先是检查范围,2. 修改modCount,3. 保留将要被移除的元素,4. 将移除位置之后的元素向前挪动一个位置,5. 将list末尾元素置空(null),6. 返回被移除的元素。

The public static void Arraycopy (object src, int srcpos, object dest, int destpos,int length) is used in conjunction with the API to see the incoming parameters to understand

Parameters:
SRC-source array.
Srcpos-The starting position in the source array.
Dest-target array.
Destpos-The starting position in the target data.
Length-The number of array elements to copy

LinkedList

The bottom layer is implemented by a two-way loop list, which has a high speed when inserting and deleting operations.

privatestaticclass Entry<E> {      E element;      Entry<E> next;      Entry<E> previous;      Entry(E element, Entry<E> next, Entry<E> previous) {          this.element = element;          this.next = next;          this.previous = previous;       }  }  

LinkedList's original storage model, one data, two pointers, one pointing to the previous node, named Previous, and one pointing to the next node, named Next.

publicLinkedList() {           header.next = header.previous = header;       }  

The beginning and ends are equal, that is, the initialization time has been set to the loop.

Add Operation
publicbooleanadd(E e) {      addBefore(e, header);      returntrue;   }  
privateaddBefore(E e, Entry<E> entry) {        new Entry<E>(e, entry, entry.previous);//-------1---------        newEntry.previous.next = newEntry;        newEntry.next.previous = newEntry;        size++;        modCount++;        return newEntry;    }

We first look at the above given the entity class, the construction method has three parameters, the second is her next field, the third is her previous domain, so the above code 1 line will be passed in the entry entity, that is, the header object as the next field of Newentry, Instead, Entry.previous is header.previous as the previous domain. This means inserting a new node between the header node and the header's predecessor node. Look at the following figure:

Good point to this, NewEntry.previous.next = NewEntry; and newEntry.next.previous = NewEntry; it's a little confusing for people who just touch the underlying code.
Split, Newentry.previous is not referring to the newEntry of the last entry, the last entry next is not NewEntry, string up is NewEntry.previous.next = NewEntry;
similarly newEntry.next.previous = NewEntry; as well.

Removal Action
     Public Boolean Remove(Object o) {if(o==NULL) { for(entry<e> e = Header.next; E! = header; e = e.next) {if(e.element==NULL) {remove (e);return true; }            }        }Else{ for(entry<e> e = Header.next; E! = header; e = e.next) {if(O.equals (e.element)) {Remove (E);return true; }            }        }return false; }
        PrivateERemove(entry<e> E) {if(E = = header)Throw NewNosuchelementexception ();//Retain the removed element: to returnE result = e.element;//The next node of the node is pointed to the node after the nodeE.previous.next = E.next;//Previous points the node's next node to the front node of the node            The node can be removed from the list by two steps: In the linked list , the node cannot be traversed to thee.next.previous = e.previous;//Return the node to emptyE.next = E.previous =NULL; E.element =NULL;            size--; modcount++;returnResult }
    1. Retain the original removal
    2. Make pointer modifications
      • E.previous.next = E.next; The next point of the removed node will be removed by the second of the Remove nodes;
      • likewise e.next.previous = e.previous;
    3. The removed node is returned to null e.next = E.previous = null;
the difference between vector and ArrayList

The next article will introduce map

Resources:
The collection Class of Java beauty [from rookie to master evolution]
Java Improvement Chapter (32)-–list Summary
Java Improvement Chapter (22)-linkedlist

Java basics of Perplexed Java-Set and List

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.