A collection of Java interview preparation (not finished)

Source: Internet
Author: User
Tags object object

Summary: Although the collection of the framework of some knowledge points, but think of the interview may be asked the source code, and then roughly the collection framework of some of the implementation of the source of the class, here to tidy up a bit.

I. Collection Framework

Two. Delve into the implementation class

1.ArrayList Source Code Implementation

ArrayList maintains a dynamic array internally, and if there is no explicit initialization, the default capacity of the dynamic array is 10, and when the array capacity is full, the capacity is expanded to 1.5 times times plus 1 each time.

ArrayList's remove, add, clear and other methods of the implementation of the principle is to operate the internal object array, it is important to note that before the Add method is executed, the capacity of the array is pre-confirmed, if full, the first expansion, here is very simple, The source code will not be parsed.

It is important to note that there is a method trimtosize, the function of this method is to remove the reserved position, when the memory is tight.

    /*** Returns The element at the specified position of this list. *     * @paramIndex Index of the element to return *@returnThe element at the specified position in this list *@throwsindexoutofboundsexception {@inheritDoc}     */     PublicE Get (intindex)        {Rangecheck (index); returnElementdata (index); }    /*** Replaces the element at the specified position in this list with * the specified element. *     * @paramIndex Index of the element to replace *@paramelement element to is stored at the specified position *@returnThe element previously at the specified position *@throwsindexoutofboundsexception {@inheritDoc}     */     PublicE Set (intindex, E Element)        {Rangecheck (index); E OldValue=Elementdata (index); Elementdata[index]=element; returnOldValue; }    /*** Appends the specified element to the end of this list. *     * @parame element to is appended to the this list *@return<tt>true</tt> (as specified by {@linkCollection#add}) */     Public BooleanAdd (e e) {ensurecapacityinternal (size+ 1);//increments modcount!!elementdata[size++] =e; return true; }    /*** Inserts the specified element at the specified position in this * list. Shifts the element currently at, if any, and * any subsequent elements to the right (adds one to their I     ndices). *     * @paramindex index at which the specified element is inserted *@paramelement element to be inserted *@throwsindexoutofboundsexception {@inheritDoc}     */     Public voidAddintindex, E Element)        {Rangecheckforadd (index); Ensurecapacityinternal (Size+ 1);//increments modcount!!System.arraycopy (Elementdata, index, Elementdata, index + 1, size-index); Elementdata[index]=element; Size++; }    /*** Removes the element at the specified position of this list.     * Shifts Any subsequent elements to the left (subtracts one from their * indices). *     * @paramIndex the index of the element to be removed *@returnThe element that is removed from the list *@throwsindexoutofboundsexception {@inheritDoc}     */     PublicE Remove (intindex)        {Rangecheck (index); Modcount++; E OldValue=Elementdata (index); intnummoved = size-index-1; if(nummoved > 0) system.arraycopy (elementdata, index+1, Elementdata, Index, nummoved); elementdata[--size] =NULL;//clear to let GC do it work        returnOldValue; }    /*** Removes the first occurrence of the specified element from this list, * if it is present.  If The list does not contain the element, it is * unchanged. More formally, removes the element with the lowest index * <tt>i</tt> such that * <tt> (O==NULL&A mp;nbsp;?  &nbsp;get (i) ==null&nbsp;:&nbsp;o.equals (get (i))) </tt> * (if such an element exists). Returns <tt>true</tt> If this list * contained the specified element (or equivalently, if this list *     Changed as a result of the call). *     * @paramo element to is removed from the this list, if present *@return<tt>true</tt> If this list contained the specified element*/     Public BooleanRemove (Object o) {if(O = =NULL) {             for(intindex = 0; index < size; index++)                if(Elementdata[index] = =NULL) {fastremove (index); return true; }        } Else {             for(intindex = 0; index < size; index++)                if(O.equals (Elementdata[index])) {fastremove (index); return true; }        }        return false; }
ArrayList

2.Vector Source Code Implementation

Vector is the same as ArrayList, also maintains a dynamic array internally, the default length of the array is 10, but the expansion scheme differs from ArrayList, The capacity of the vector after expansion depends on the expansion factor Capacityincremen and the old array capacity oldcapacity, the law is as follows: int newcapacity = (capacityincrement > 0)? (Oldcapacity + capacityincrement): (oldcapacity * 2), note: After calculating the new array size, also to compare with the minimum and maximum values defined within the vector class, if the upper and lower limits, then the new array capacity is equal to the upper and lower bounds. In addition, if the scaling factor is not passed in during initialization, the expansion factor defaults to 0.

Vector basic additions and deletions and other operations to achieve the same principle and ArrayList, are simple to operate the array.

Vector is thread-safe, the way to implement is to add the Synchronized keyword in the basic operation method to decorate, so that this method can only be accessed at the same time by one thread, so as to ensure the security of multi-threaded access.

The inside of the vector also implements an iterator, but it is implemented using enumeration.

     PublicEnumeration<e>elements () {return NewEnumeration<e>() {            intCount = 0;  Public Booleanhasmoreelements () {returnCount <Elementcount; }             PublicE nextelement () {synchronized(Vector. This) {                    if(Count <Elementcount) {                        returnElementdata (count++); }                }                Throw NewNosuchelementexception ("Vector enumeration");    }        }; }
Vector

3.LinkedList

LinkedList is implemented internally through a doubly linked list, and each incoming object is transformed into a node (both entry and node are implemented through an inner class). LinkedList the implementation of the basic operation is through the link List node address assignment or NULL to achieve, specifically, link and unlink similar method.

    Private Static classNode<e>{E item; Node<E>Next; Node<E>prev; Node (node<E> prev, E element, node<e>next) {             This. Item =element;  This. Next =Next;  This. prev =prev; }    }     Public BooleanAdd (e e) {linklast (e); return true; }     Public BooleanRemove (Object o) {if(O = =NULL) {             for(node<e> x = first; X! =NULL; x =x.next) {if(X.item = =NULL) {unlink (x); return true; }            }        } Else {             for(node<e> x = first; X! =NULL; x =x.next) {if(O.equals (X.item)) {unlink (x); return true; }            }        }        return false; }
LinkedList

4.HashSet

HashSet internal is through the HashMap bottom to achieve, but is HashMap value is all assigned to a constant object object, internal additions and deletions and other methods are directly called HashMap method, so do not repeat, and so on, such as HashMap in-depth analysis.

 private  transient  hashmap<e,    Object> map;  private  static  final  object PRESENT = new   object (        );  public  boolean   add (e e) { return  map.put (E, PRESENT) ==null  ;  public  boolean   remove (Object o) { return  map.remove (o) ==present; }
HashSet

5.TreeSet

TreeSet is implemented internally through the TreeMap, and is the same as HashSet, which sets value to a constant.

6.HashMap

HashMap the bottom layer is implemented through the data structure of the array-linked list, why use the form of the data-linked list? This leads to a very important problem, is the hash conflict problem, we all know that for hashxxx this implementation class, the method of ensuring key uniqueness is the hashcode and the Equals method, when the element is deposited into the hashmap, the key is detected, Determine if the same key already exists,

A collection of Java interview preparation (not finished)

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.