[Java] Simulation and realization of ArrayList and LinkedList

Source: Internet
Author: User
Tags int size

The list in Java inherits from the collection interface. The list is an ordered collection, using this interface to precisely control where each element is inserted. The user is able to access the elements in the list using an index (where the element is positioned in the list, similar to an array subscript), similar to an array of java. Unlike set sets, the list allows repeating elements. For E1 and E2 object elements that meet the E1.equals (E2) condition, they can exist in the list collection at the same time. Of course, there is also a list implementation class that does not allow the existence of duplicate elements. In addition to the iterator () method, which has the collection interface prerequisites, the list also provides a listiterator () method that returns a Listiterator interface, compared to the standard iterator interface. Listiterator has a number of add () methods that allow you to add, delete, set elements, and traverse forward or backward.

The common classes that implement the list interface are linkedlist,arraylist, where the characteristics of the two lists are simulated to deepen understanding.


One, Two-way linked list linkedsequence:


A) Private member variables:

Private Entry head;private int cnt;

I. Head is the entry of each linkedsequence head pointer, through which it is able to access all the internal data of the object, noting that head does not store data, but only as a head node tag.
The entry structure is described in detail below.
Ii. CNT records the number of members within each linkedsequence, creating a Private Method SetSize () alignment to facilitate the use of internal classes.


b) private internal static class:

private static class Entry {Sequenceitem si; Entry Befo; Entry Next; Entry (Sequenceitem si, Entry befo, Entry next) {this.si = Si;this.befo = Befo;this.next = Next;}}

Each entity contains a Sequenceitem-type Private member variable Si, which points to the previous entry reference Befo, pointing to the next entry reference next.
C constructor function:
Linkedsequence () {head = new Entry (null, NULL, NULL); Head.next = Head;head.befo = head;cnt = 0;}

I. Initialize head, all data members are empty;
Ii. Mark the next and befo of the head as themselves;
Iii. The CNT count is zeroed.


d) public methods:

I. public void Add (Sequenceitem Item) chain footer adds the item element:
Create a entry-type TMP, whose SI is item,befo the head of the Befo (head befo points to the last entry in the list), and next is head.
The original end element's next is marked as TMP, and the head's BEFO points to the new end element, TMP.
Counter CNT plus one.

Ii. public Sequenceitem get (int i) gets the first element of the list, starting with the subscript 0:
If index i exceeds [0, CNT], an out-of-bounds exception is thrown.
Create entry E to point to the first element, iterate through next I, and return to the e.si at this time.

Iii. public void Remove (Sequenceitem item) deletes the first item element in a linked list:
If item is empty, do not process;
Create entry E to point to the first element, according to the E-scan list, if an e's SI is equal to item, create a entry tmp that points to E at this point, mark the next node of E as the successor of E, and mark the befo of the successor of E as the precursor node of E.
The Befo, next, and SI of TMP are marked as NULL, and the counter CNT is reduced by one.
Throws a Nosuchelementexception exception if it is not found after traversing the entire list.

iv. Public boolean contains (Sequenceitem item) determines whether the list contains the item element:
Similar to the Remove () operation, except that returns true and false does not do allocations.

v. public int size () returns the length of the linked list: returns CNT.

Vi. Public boolean isEmpty () determines whether the linked list is empty:
Return to cnt==0?

vii. public sequenceitem[] ToArray () converts a linked list to an array:
Create a Sequenceitem array of cnt size ans, and sequentially put the SI of each node E in the list into ans.

viii. public boolean equals (Sequence seq) determines whether two linked list elements are relative:
If the size of the two sequence is not equal, the comparison is no longer made and returns false directly.
Otherwise, the entire element of two sequence is compared, and false is returned once it contains a different one.

Ix. public String toString () converts the linked list to a string:
Similar to ToArray, except that the original ans was stored in string and returned to arrays.tostring (ans) at the end of the put.

X. Public Seqiterator iterator () forward iterator:
Returns an internal anonymous class object of Seqiterator, containing the private member variable index, which records the relative position of the current access element, initialized to 0;entry e records the node that is currently being accessed, and initializes the first element of the list.
public boolean Hasnext (): Returns whether index is less than LinkedSequence.this.size ().
Public Sequenceitem Next (): Returns the current E.si,index plus 1,e points to e.next.
Remove from public void (): The previous element can be deleted only if index is greater than 0 o'clock, and the delete operation is the same as remove (). Note After deletion, you need to reduce the index by one!

Xi. public seqiterator reverseiterator () reverse iterator:
Returns an Seqiterator internal anonymous class object that contains the private member variable index, records the relative position of the current access element, initializes it to size () -1;entry e Records the node that is currently being accessed, and initializes the last element of the list.
public boolean Hasnext (): Returns whether index is greater than-1.
Public Sequenceitem Next (): Returns the current E.si,index minus 1,e points to e.befo.
Remove from public void (): Only if index is less than size ()-1, the latter element can be deleted, and the delete operation is the same as remove (). Note You do not have to modify index at this time.

xii. public Biseqiterator biiterator () bidirectional iterator:
That is, the synthesis of the first two types of iterators.


Two, variable-length array arraysequence:

A) Private member variables:

Private sequenceitem[] Sequenceitemarray = new sequenceitem[2];p rivate int cnt = 0;

I. Sequenceitemarray for each arraysequence data storage array.
Ii. CNT records the number of members within each arraysequence, different from the size of the array.

b) constructor:

Arraysequence () {Sequenceitemarray = new sequenceitem[2];cnt = 0;}

I. The Sequenceitemarray initialization size is 2;
Ii. The CNT count is zeroed.

c) public methods: basically similar to linkedsequence, the main difference is the Add () and remove () operations.
I. public void Add Item element in the Sequenceitem array:
First ensure that the size of the Sequenceitemarray can be installed cnt+1 elements, if the size of the Sequenceitemarray, you need to expand the current array size to the original one times, and then put the item, the counter CNT plus one.

Ii. public void Remove (Sequenceitem item) deletes the first item element in a linked list:
First, in the Sequenceitemarray to look for the subscript of item, as I, then the CNT-I-1 elements will need to move forward, then the cnt-1 subscript disposition is empty.
The above completion of the deletion, need to re-determine the size of the container, if the current CNT is less than 1/4 of the length of Sequenceitemarray, you can shorten the length of the Sequenceitemarray by half, similar to the method of expansion.

Third, performance comparison:

Iv. Source code:

Sequence interface:

Import Java.util.*;interface Sequence {void Add (Sequenceitem item); Sequenceitem get (int i), void Remove (Sequenceitem item), Boolean contains (Sequenceitem item), int size (), Boolean isEmpty ( ); Seqiterator iterator (); Seqiterator Reverseiterator (); Biseqiterator Biiterator (); Sequenceitem[] ToArray (); Boolean equals (Sequence seq); String toString ();}

Seqiterator Interface:

Interface Seqiterator {Boolean hasnext (); Sequenceitem next (); void remove ();}

Data member Sequenceitem class:

public class Sequenceitem {private string Data;public string GetData () {return data;} public void SetData (String s) {data = new String (s);} public boolean equals (Sequenceitem si) {return this.getdata (). Equals (Si.getdata ());}}

Bidirectional linked list linkedsequence:

Import java.util.*;p Ublic class Linkedsequence implements Sequence {private Entry head;private int cnt;private static clas s Entry {Sequenceitem si; Entry Befo; Entry Next; Entry (Sequenceitem si, Entry befo, Entry next) {this.si = Si;this.befo = Befo;this.next = Next;}} Linkedsequence () {head = new Entry (null, NULL, NULL); Head.next = Head;head.befo = head;cnt = 0;} public void Add (Sequenceitem item) {Entry TMP = new Entry (item, HEAD.BEFO, head); tmp.befo.next = Tmp;head.befo = tmp;cnt++ ;} Public Sequenceitem get (int i) {if (I >= cnt | | < 0) {throw new Indexoutofboundsexception ();} Entry e = head.next;for (int j = 0; J < i; J + +) {e = E.next;} return e.si;} public void Remove (Sequenceitem item) {if (item = = null) {return;} Entry e = head.next;for (int i = 0; i < cnt; i++) {if (Item.equals (e.si)) {Entry tmp = E;tmp.befo.next = TMP.NEXT;TMP.N Ext.befo = Tmp.befo;tmp.befo = Null;tmp.next = Null;tmp.si = Null;cnt--;return;} e = E.next;} throw new Nosuchelementexception ();} public Boolean ContaINS (Sequenceitem Item) {if (item = = NULL) {return false;} Entry e = head.next;for (int i = 0; i < cnt; i++) {if (Item.equals (e.si)) {return true;} e = E.next;} return false;} public int size () {return this.cnt;} private void setSize (int cnt) {//use for inner class to modify cntthis.cnt = cnt;//System.out.println ("CNT:" +this.cnt); }public Boolean isEmpty () {return this.cnt==0? True:false;} Public Seqiterator iterator () {return new Seqiterator () {private int index = 0;private Entry e = Head.next;public Boolean Hasnext () {return index<linkedsequence.this.size ();} Public Sequenceitem Next () {Sequenceitem res = E.si;e = E.next;index++;return res;} public void Remove () {if (Index > 0) {Entry tmp = E.befo;tmp.befo.next = TMP.NEXT;TMP.NEXT.BEFO = TMP.BEFO;TMP.BEFO = n Ull;tmp.next = Null;tmp.si = null;index--; LinkedSequence.this.setSize (LinkedSequence.this.size ()-1);}};} Public Seqiterator Reverseiterator () {return new Seqiterator () {private int index = LinkedSequence.this.size () -1;privateEntry E = head.befo;public Boolean hasnext () {return index>-1;} Public Sequenceitem Next () {Sequenceitem res = E.si;e = E.befo;index--;return res;} public void Remove () {if (Index < LinkedSequence.this.size ()-1) {Entry tmp = E.next;tmp.befo.next = tmp.next;tmp.next.b EFO = Tmp.befo;tmp.befo = Null;tmp.next = Null;tmp.si = null; LinkedSequence.this.setSize (LinkedSequence.this.size ()-1);}};} Public Biseqiterator Biiterator () {return new Biseqiterator () {private int index = 0;private Entry e = head.next;public bo Olean Hasnext () {return index<linkedsequence.this.size ();} Public Sequenceitem Next () {Sequenceitem res = E.si;e = E.next;index++;return res;} public void Remove () {if (Index > 0) {Entry tmp = E.befo;tmp.befo.next = TMP.NEXT;TMP.NEXT.BEFO = TMP.BEFO;TMP.BEFO = n Ull;tmp.next = Null;tmp.si = null;index--; LinkedSequence.this.setSize (LinkedSequence.this.size ()-1);}} public Boolean hasprevious () {//SYSTEM.OUT.PRINTLN (index); return index>-1;} Public Sequenceitem Previous () {SequEnceitem res = E.si;e = E.befo;index--;return res;}};} Public sequenceitem[] ToArray () {sequenceitem[] ans = new sequenceitem[cnt]; Entry e = head.next;for (int i = 0; i < cnt; i++) {Ans[i] = E.si;e = E.next;} return ans;} public boolean equals (Sequence seq) {//?if (this.size ()! = Seq.size ()) {return false;} Entry e1 = this.head.next;for (int i = 0; i < cnt; i++) {if (!e1.si.equals (Seq.get (i))) {return false;} e1 = E1.next;} return true;} Public String toString () {string[] s = new string[cnt]; Entry e = head.next;for (int i = 0; i < cnt; i++) {S[i] = E.si.getdata (); e = E.next;} return arrays.tostring (s);}}

Variable-length array arraysequence:

Import java.util.*;p Ublic class Arraysequence implements Sequence {private sequenceitem[] sequenceitemarray;private int Cnt Arraysequence () {Sequenceitemarray = new sequenceitem[2];cnt = 0;} private void ensurecapacity (int currcapacity) {if (currcapacity >= sequenceitemarray.length) {int newcapacity = Sequen Ceitemarray.length<<1;sequenceitemarray = arrays.copyof (Sequenceitemarray, newCapacity);} else if (Currcapacity < SEQUENCEITEMARRAY.LENGTH/4) {int newcapacity = sequenceitemarray.length>>1; Sequenceitemarray = arrays.copyof (Sequenceitemarray, newcapacity);}} public void Add (Sequenceitem item) {ensurecapacity (cnt+1); sequenceitemarray[cnt++] = Item;} Public Sequenceitem get (int i) {return sequenceitemarray[i];} public void Remove (Sequenceitem item) {if (item! = NULL) {for (int i = 0; i < cnt; i++) {if (Item.equals (Sequenceitemar Ray[i]) {int nummoved = cnt-i-1;if (nummoved > 0) {system.arraycopy (Sequenceitemarray, i+1, Sequenceitemarray, I, NumM Oved);} SequenceitemarrAY[--CNT] = null;ensurecapacity (CNT); return;}}} Public Boolean contains (Sequenceitem item) {for (int i = 0; i < cnt; i++) {if (Item.equals (Sequenceitemarray[i])) {Retu RN true;}} return false;} public int size () {//System.out.println (cnt+ "," +sequenceitemarray.length); return CNT;} public Boolean isEmpty () {return cnt==0? True:false;} Public Seqiterator iterator () {return new Seqiterator () {private int index = 0;public Boolean hasnext () {return index<c NT;} Public Sequenceitem Next () {return sequenceitemarray[index++];} public void Remove () {if (Index > 0) {ArraySequence.this.remove (ArraySequence.this.get (--index));}};} Public Seqiterator Reverseiterator () {return new Seqiterator () {private int index = ArraySequence.this.size () -1;public bo Olean Hasnext () {return index>-1;} Public Sequenceitem Next () {return ArraySequence.this.get (index--);} public void Remove () {ArraySequence.this.remove (ArraySequence.this.get (index+1)); if (Index >= ArraySequence.this.size ()) {index = ArraysequencE.this.size ()-1;}};} Public Biseqiterator Biiterator () {return new Biseqiterator () {private int index = 0;public Boolean hasnext () {return Inde X<arraysequence.this.size ();} Public Sequenceitem Next () {return ArraySequence.this.get (index++);} public void Remove () {if (Index > 0) {ArraySequence.this.remove (ArraySequence.this.get (--index));}} public Boolean hasprevious () {return index>0;} Public Sequenceitem Previous () {return ArraySequence.this.get (--index);};} Public sequenceitem[] ToArray () {return sequenceitemarray;} public boolean equals (Sequence seq) {if (This.size ()!=seq.size ()) {return false;} for (int i = 0; i < this.size (); i++) {if (!this.get (i). Equals (Seq.get (i))) {return false;}} return true;} Public String toString () {string[] s = new String[cnt];for (int i = 0; i < cnt; i++) {S[i] = Sequenceitemarray[i].getda Ta ();} return arrays.tostring (s);}}

Test procedure Test.java:

Import java.util.*;p ublic class Test {public static void main (string[] args) {//Sequence test = new Linkedsequence (); Sequence test = new Arraysequence (); Sequenceitem tmp = new Sequenceitem ();//Test Add (), size () for (int cnt =, cnt <= 1000000; CNT *=) {int Testtim  E = 10;double ans = 0;double[] res = new Double[testtime];while (Testtime > 0) {//Date begin = new Date (); for (int i = 0; I < CNT; i++) {Tmp.setdata (string.valueof (i)); Test.add (TMP);//System.out.println (Test.size ());} Date end = new Date ();//Date begin = new Date ();//for (int i = 0; i < cnt; i++) {//tmp = Test.get (0);///System  . Out.println (Tmp.getdata ());//Test.remove (TMP),//}//Date end = new Date (),//Date begin = new Date ();/for (int i = 0; I < CNT; i++) {//tmp = Test.get (i);///System.out.println (Tmp.getdata ());//}//Date end = new Date (); Seqiterator si = test.iterator ();D ate begin = New Date (), while (Si.hasnext ()) {Si.next ();} Date end = new Date (); Res[--testtime] = (double) end.getTime ()-begin.gettime ())/1000;ans + = Res[testtime];} SYSTEM.OUT.PRINTLN (arrays.tostring (res)); System.out.println (ans);} Test Add (), get ()//for (int i = 0; i < i++) {//Sequenceitem TMP = new Sequenceitem ();//Tmp.setdata (String.val Ueof (i));//Test.add (TMP);//System.out.println (Test.get (i). GetData ());//}//Test iterator (), reverseiterator ()// Seqiterator si = Test.iterator (),//while (Si.hasnext ()) {//System.out.println (Si.next (). GetData ());//Si.remove ();// }//System.out.println (Test.isempty ());//si = Test.reverseiterator ();//while (Si.hasnext ()) {//System.out.println ( Si.next (). GetData ());//Si.remove ();//}//System.out.println (Test.isempty ());//test Biiterator ()//Biseqiterator BSI = Test.biiterator ();//while (Bsi.hasnext ()) {//System.out.println ("Test Next:");//System.out.println (Bsi.next () . GetData ());///Bsi.remove ();//}//System.out.println (Test.isempty ());//Bsi.previous ();/while (Bsi.hasprevious ( ) {//System.out.println ("Test previous:");//SYSTEM.OUT.PRIntln (Bsi.previous (). GetData ());//}//System.out.println (Test.isempty ());//test toString ()//SYSTEM.OUT.PRINTLN ( test);//Test IsEmpty (), get (), remove (), contains (), size ()//while (!test.isempty ()) {//Sequenceitem TMP = test.get (0); System.out.println (Tmp.getdata ());//Test.remove (TMP);//System.out.println (Test.size ());//System.out.println ( Test.contains (TMP)),//}}}




[Java] Simulation and realization of ArrayList and LinkedList

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.