Implementation code for a simple dynamic array

Source: Internet
Author: User
Tags addall throw exception

The following is my dynamic array implementation of the source code, for reference only, please correct me:

Import java.util.*;p Ublic class My_list implements collection{/**************************************************** Test module//Main method, test with public static void main (String [] args) {/*my_list ma = new my_list ();//Test Add Method Ma.add ("abc"); Ma.add ("ASDFJ"); System.out.println (Ma.size ());//Test Get Method System.out.println (Ma.get (0)); System.out.println (Ma.get (1));//test Add Method two Ma.add (1, "changed value"); System.out.println (Ma.get (1));//test AddAll method List lis = new ArrayList (); Lis.add ("1"); Lis.add ("2"); Lis.add ("3"); Ma.addall (1,lis); System.out.println ("Length after execution of AddAll" + ma.size ()); System.out.println ("The fourth element after executing addall is" + ma.get (3));//test clear function//ma.clear ();//system.out.println (" The number of elements after the clear function executes (+ ma.size ());//test contains Method System.out.println ("Does it contain 1 strings?"). "+ Ma.contains (" 1 ")); System.out.println ("Does it contain 23 strings?") "+ Ma.contains");//lis.add ("ASDDFJ");//test Containsall Method System.out.println ("Ma contains all elements of the LIS? "+ Ma.containsall (LIS));//test Equals method my_list Lis2 = new My_list (); Lis2.add (" abc "); Lis2.add (" 123 "); Lis2.add (" Me and You "); My_list Lis3 = new My_list (); Lis3.add ("abc"); Lis3.add ("123"); Lis3.add ("I He"); Boolean b3 = Lis2.equals (LIS3); SYSTEM.OUT.PRINTLN (B3);//test indexOf method//lis.add (null);//int index_firstnull = Lis.indexof (null); Lis.add (" Asdjsdfaasdaa "); Lis.add (null); System.out.println ("3 first occurrence index is" + Lis.indexof ("3"));//test Lastindexoflis.add (NULL); Lis.add ("Me and You"); Lis.add (null); Lis.add ("3");  System.out.println ("Last show me and your Place" + Lis.lastindexof ("Me and You"));//Test IsEmptySystem.out.println ("Lis.isempty? "+ lis.isempty ()); My_list lis_isempty = new My_list ();  System.out.println ("Lis_isempty.isempty? "+ lis_isempty.isempty ());//Test RemoveSystem.out.println (" The length of the LIS before remove is "+ lis.size ()); System.out.println ("Remove, the value of index = 2 is" + Lis.get (2)); System.out.println ("Remove", the value of index = 6 is "+ lis.get (6)"),//lis.remove (null),//lis.remove (1); System.out.println ("The length of the LIS after remove is" + lis.size ()); System.out.println ("Remove, the value of index = 1 is" + lis.get (1)); System.out.println ("Remove, the value of index = 4 is" + Lis.get (4)); *///removeallTest my_list lis = new My_list () Lis.add ("1"); Lis.add ("2"); Lis.add ("3"); Lis.add ("Me and You"); Lis.add (null); Lis.add ("4"); Lis.add ("5"); Lis.add ("6");/*system.out.println ("The length of the LIS before RemoveAll is" + lis.size ()); System.out.println ("Before RemoveAll, the value of index = 1 is" + lis.get (1)); List Lis_removeall = new ArrayList (), Lis_removeall.add ("Me and You"), Lis_removeall.add ("3"); Lis_removeall.add (null); Lis.removeall (Lis_removeall);//system.out.println ("Before RemoveAll, the value of index = 6 is" + lis.get (6));; System.out.println ("The length of the LIS after RemoveAll" + lis.size ()); System.out.println ("After RemoveAll, the value of index = 3 is" + Lis.get (3)); System.out.println ("RemoveAll", the value of index = 4 is "+ Lis.get (4)"), *///method Retainall Test/*list Lis_retainall = new ArrayList (); Lis_retainall.add ("1"); Lis_retainall.add ("2"); Lis_retainall.add ("Me and You"); Lis_retainall.add ("null");//lis_ Retainall.add (); SYSTEM.OUT.PRINTLN ("Size of the LIS before executing the Retainall method =" + lis.size ()); Lis.retainall (Lis_retainall); SYSTEM.OUT.PRINTLN ("Size of the LIS after executing the Retainall method =" + lis.size ()); System.out.println ("Finished Retainall method after the value of the LIS output = "); System.out.println (Lis.get (2)); *///set method Test/*lis.set (2, "Soga"); System.out.println ("Index 2 value replaced after" + Lis.get (2)); Test of//sublist method my_list ml = new my_list (); ml = lis.sublist (2,4); SYSTEM.OUT.PRINTLN ("sublist returns the object length =" + ml.size ()); System.out.println ("Where the value of index 1 is =" + ml.get (1)); *//*//test toarrayobject [] ob_test1 = new object[]{"2", "4", "Akjsdf", "Me and You", Null};object [] ob = Lis.toarray (Ob_test1); System.out.println ("ToArray length is" + ob.length); System.out.println ("The first value of the returned array is" + ob[0]); *///Iterative method Test/*iterator it = Lis.iterator (); while (It.hasnext ()) { System.out.println (It.next ()); It.remove ();//it.remove ();} SYSTEM.OUT.PRINTLN ("size after iteration =" + lis.size ()); *///returns the hash value method Test int has = Lis.hashcode (); SYSTEM.OUT.PRINTLN ("List hash value is" + has);} /********************************************************************///my_list code/** member Variable */object [] Object = null ;//initial array length int len = 10;//defines the length of each increment int addlen = 10;//Dynamic array current element number private int size;//construction method Public My_list () {object = new object [len];size = 0;} /** The following is the implementation of CollEction method *///add Method A public boolean Add (Object OB) {Boolean RTN = false;//determines the number of current dynamic array objects if (size = = Object.length) {// Corresponding total length growth len = len + 10;//If the current array is full, re-put it in another array//define an array to store the current array value object [] Object_before = Object;object = new Object[len ];for (int i = 0;i<size;i++) {Object[i] = object_before[i];} Perform add operation object[size] = ob;size++;} Else{object[size] = ob;size++;} RTN = True;return Rtn;} Add method Two, index out of range throws exception public void Add (int index,object ob) {if (index<0| | index>size-1) {New RuntimeException ("Indexoutofboundsexception");} Else{object[index] = OB;}} AddAll method Public boolean addall (int index,collection c) {Boolean RTN = false;if (index<0| | index>size-1) {throw new RuntimeException ("Indexoutofboundsexception");} else if (c==null) {throw new RuntimeException ("NullPointerException");} else{for (int i = 0;i<c.size (); i++) {Add (C.toarray () [i]);} RTN = true;} return RTN;} public boolean AddAll (Collection c) {Boolean RTN = False;int Size_before = size;for (int i = 0;i<c.toarray (). length;i++) { Add (C.toaRray () [i]);} if (size_before! = size) {RTN = true;} return RTN;} Remove all elements public void clear () {for (int i = 0;i<size;i++) {Object[i] = 0;} size = 0;} Determines whether to include the specified element public boolean contains (Object ob) {Boolean RTN = false;for (int i = 0;i<size;i++) {if (OB = = null) {if (object[ I] = = null) {RTN = True;break;}} Else{if (Ob.equals (Object[i])) {RTN = True;break;}}} return RTN;} Determines whether to include all elements of Collection public boolean containsall (Collection c) {for (int i = 0;i<c.size (); i++) {if (!contains ( C.toarray () [i]) {return false;}} return true;} The Equals method public boolean equals (Object ob) {Boolean RTN = true;//First determines whether the object is a list if (Ob.getclass (). GetName (). Equals ("My_ List ")) {//To determine whether the lengths are consistent if (((my_list) OB). Size () ==size) {//To determine if the corresponding position corresponds to the element is equal for (int i = 0;i<size;i++) {if (!) ( ((my_list) OB). get (i). Equals (Object[i])) {return false;}} Else{rtn = false;}} Else{rtn = false;} return RTN;} Get method, out of range throw exception public Object get (int index) {Object RTN = null;if (index<0| | index>size-1) {throw new ArrayIndexOutOfBoundsException ("Indexoutofboundsexception");} ElSe{rtn = Object[index];} return RTN;} Returns the hash code value of the table (not implemented) public int hashcode () {int RTN = 0;int Hashcode = 1;iterator i = Iterator (), while (I.hasnext ()) {Object obj = I.next (); hashcode = 31*hashcode + (obj==null? 0:obj.hashcode ());} RTN = Hashcode;return Rtn;} Returns the index of the first occurrence of the element that does not exist, returns -1public int indexOf (Object ob) {int RTN = -1;//Determines whether the element in Object and list is compatible for (int i = 0;i<size;i++) {if (Object[i] = = null) {if (OB = = null) {return i;}} Else{if (Object[i].equals (ob)) {return i;}}} return RTN;} Returns the location of the last occurrence of this element public int lastIndexOf (Object ob) {int RTN = -1;for (int i = size-1;i>=0;i--) {if (object[i] = = null) {if (ob = = null) {return i;}} Else{if (Object[i].equals (ob)) {return i;}}} return RTN;} Determines whether the list contains elements public boolean IsEmpty () {Boolean RTN = true;if (size! = 0) {Rtn = false;} return RTN;} Returns an iterator that iterates in the appropriate order public Iterator Iterator () {Iterator RTN = Null;rtn = new My_iterator (this); return RTN;} Removes an element that returns the removed element if the passed-in index value goes out of range throws an exception to public Object remove (int index) {Object RTN = null;if (index<0| | Index>=size) {throw new RuntimEexception ("Indexoutofboundsexception");} ELSE{RTN = object[index];for (int i = index;i<size-1;i++) {Object[i] = object[i+1];} size--;} return RTN;} public boolean remove (Object ob) {boolean RTN = False;int index = indexOf (OB), if (index!=-1) {Remove (index), Rtn = true;} return RTN;} Remove all elements (problem start) public boolean removeall (Collection c) {Boolean RTN = false;//stores the current size value, which is used to determine if the list has elements that have changed int size_ before = Size;object [] Ob_toarray = C.toarray (); for (int i = 0;i<c.size (); i++) {remove (Ob_toarray[i]);} Because when C is the object itself, it is in the process of being changed, so if (this = = null && c = = NULL) is processed separately | | This.equals (c)) {clear ();} Determine if the elements in the table have changed if (Size_before = = size) {RTN = true;} return RTN;} Keep elements in list (code quality issues) (question) public boolean retainall (Collection c) {Boolean RTN = false;// Defines an reshape variable that stores the current Siez so that it can be used to determine whether the value of the list has changed int size_before = Size;object [] Ob_toarray = C.toarray (); for (int i = 0;i<size;i++) {f or (int j = 0;j<ob_toarray.length;j++) {if (object[i]==null) {if (ob_toarray[j]==null) {break;}} Else{if (Object[i].equals (Ob_toarray[j])) {break;}} if (j==ob_toarray.length-1) {//does not find the corresponding element after traversal, executes removeremove (i);//Because the distribution of elements in the original dynamic array occurs before the remove, so i--i--;}}} if (size_before!=size) {RTN = true;} return RTN;} Replace element, return previous element public Object set (int index,object ob) {Object RTN = Null;rtn = Object[index];object[index] = Ob;return RTN;} Size () returns the number of elements in the list public int size () {return size;} Returns elements from FromIndex to Toindex, before including the public my_list sublist (int fromindex,int toindex) {my_list RTN = null;if ((fromIndex >toindex) | | (fromindex<0) | | (toindex>size-1)) {throw new RuntimeException ("Indexoutofboundsexception");} Else{rtn = new My_list (); for (int i = fromindex;i<toindex;i++) {Rtn.add (Get (i));}} return RTN;} Returns all elements public object[] ToArray () {Object [] Rtn = NULL;RTN = Object;return Rtn;} Returns the element in the list public object[] ToArray (object [] ob) {Object [] Rtn = null; My_list ml = new My_list (), for (int i = 0;i<ob.length;i++) {if (contains (Ob[i])) {Ml.add (ob[i]);}} RTN = Ml.toarray (); return RTN;}} /*************************************************************************///iteratorsImplementation class My_iterator implements Iterator{my_list ml = null;object [] Object = null;//Define Constructor public my_iterator (My_list ml) {this.ml = Ml;object = Ml.toarray ();} /** The following is a method for implementing the Iterator Interface */public Boolean Hasnext () {Boolean RTN = True;if (point> (Ml.size ()-1)) {RTN = false;} return RTN;} Defines a pointer variable that is used to store the current cursor at next when private int point = 0;public object Next () {//each time the next method is called, the pointer variable is pointed to the initial position Object RTN = null;if ( Point> (Ml.size ()-1)) {throw new RuntimeException ("Nosuchelementexception");} Else{rtn = Object[point];p oint++;remove_canused = true;} return RTN;} Defines a Boolean variable to mark if remove has been invoked, and the variable is initialized to True after the next method call and is initialized to falsprivate Boolean remove_canused = False after remove is called; public void Remove () {///determines if the current point is consistent with if (remove_canused) {ml.remove (point-1);//Minus one here because the pointer variable has been increased since the next operation above/ Because the order of the list corresponding to the action after remove has also changed, the pointer correspondingly follows the 1point--;} Else{throw new RuntimeException ("IllegalStateException");} remove_canused = false;}}

Code is a bit long, you need to refer to the shortcomings of the point please correct!

Implementation code for a simple dynamic array

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.