/**
* Implement ArrayList yourself
* @author Zyyt
*
*/
public class Sjbarraylist {
Storing elements in the Sjbarraylist
Transient object[] elementdata;
How many elements are in a sjbarraylist
private int size;
Construction method
Public Sjbarraylist () {
This (10);
}
Public sjbarraylist (int initialcapacity)
{//Initialize the Elementdata
if (initialcapacity > 0) {
This.elementdata = new Object[initialcapacity];
} else if (initialcapacity = = 0) {
This.elementdata = new Object[0];
} else {
throw new IllegalArgumentException ("Illegal capacity:" +
initialcapacity);
}
}
Determines whether the sjbarraylist contains an element if it does not contain an element that returns true if it contains false
public Boolean isEmpty () {
return size = = 0;
}
Returns the number of elements contained in this sjbarraylist
public int size () {
return size;
}
Add an Element
public void Add (Object obj)
{
if (size = = Elementdata.length) {
object[] Array = new object[size * 2 +1];
system.arraycopy (elementdata, 0, array, 0, elementdata.length);
elementdata = array;
}
elementdata[size++] = obj;
}
Gets the element in the corresponding index
Public Object get (int index) {
if (index<0 | | index >= size) {
System.out.println ("Index exceeds the maximum index value or index is less than 0");
return null;
}
return Elementdata[index];
}
Delete the value of the corresponding index
Public Object Remove (int index) {
if (Index < 0 | | | index > Size) {
System.out.println ("Index less than 0, or out of bounds");
System.exit (0);
}
Object OldValue = this.get (index);
System.arraycopy (elementdata, index + 1,elementdata, index, size);
elementdata[size--] = null;
return oldValue;
}
Pick up the values in the corresponding index
Public Object Set (int index,object obj)
{
if (Index < 0 | | | index > Size) {
System.out.println ("Index less than 0, or out of bounds");
System.exit (0);
}
Object OldValue = this.get (index);
Elementdata[index] = obj;
return oldValue;
}
Empty sjbarraylist
public void Clear () {
for (int i=0;i<size;i++) {
Elementdata[i] = null;
}
size = 0;
}
public static void Main (string[] args) {
Sjbarraylist sjblist = new Sjbarraylist ();
Sjblist.add ("111");
Sjblist.add ("2222");
Sjblist.add ("3333");
Sjblist.add ("4444");
Sjblist.add ("5555");
Sjblist.add ("66666");
Sjblist.remove (2);
System.out.println (Sjblist.get (3));
for (int i=0;i<sjblist.size (); i++) {
System.out.println (Sjblist.get (i));
}
}
}
Java in Sjbarraylist itself simple implementation ArrayList