1
+ package com .coding .basic ;
2
+
3
+ import java .util .Arrays ;
4
+ import java .util .ConcurrentModificationException ;
5
+ import java .util .NoSuchElementException ;
6
+
7
+ public class ArrayList implements List {
8
+
9
+ private Object [] elements ;
10
+
11
+ private int size ;
12
+
13
+ public ArrayList (int initialCapacity ) {
14
+ super ();
15
+ if (initialCapacity < 0 )
16
+ throw new IllegalArgumentException ("Illegal Capacity: " + initialCapacity );
17
+ this .elements = new Object [initialCapacity ];
18
+ }
19
+
20
+ public ArrayList () {
21
+ this (10 );
22
+ }
23
+
24
+ public void add (Object obj ) {
25
+ ensureCapacity (size + 1 );
26
+ elements [size ++] = obj ;
27
+
28
+ }
29
+
30
+ public void add (int index , Object obj ) {
31
+ rangeCheck (index );
32
+ ensureCapacity (size + 1 );
33
+ System .arraycopy (elements , index , elements , index + 1 , size - index );
34
+ elements [index ] = obj ;
35
+ size ++;
36
+ }
37
+
38
+ public Object get (int index ) {
39
+ rangeCheck (index );
40
+ return elements [index ];
41
+ }
42
+
43
+ public Object remove (int index ) {
44
+ rangeCheck (index );
45
+ Object toRemove = elements [index ];
46
+ int numMoved = size - index - 1 ;
47
+ if (numMoved > 0 )
48
+ System .arraycopy (elements , index + 1 , elements , index , numMoved );
49
+ elements [--size ] = null ;
50
+ return toRemove ;
51
+ }
52
+
53
+ public int size () {
54
+ return size ;
55
+ }
56
+
57
+ public Iterator iterator () {
58
+ return new ArrayListIterator ();
59
+ }
60
+
61
+ private void ensureCapacity (int minCapacity ) {
62
+ int oldCapacity = elements .length ;
63
+ if (minCapacity > oldCapacity ) {
64
+ int newCapacity = oldCapacity * 2 ;
65
+ if (newCapacity < minCapacity )
66
+ newCapacity = minCapacity ;
67
+ elements = Arrays .copyOf (elements , newCapacity );
68
+ }
69
+ }
70
+
71
+ private void rangeCheck (int index ) {
72
+ if (index >= size )
73
+ throw new IndexOutOfBoundsException (outOfBoundsMsg (index ));
74
+ }
75
+
76
+ private String outOfBoundsMsg (int index ) {
77
+ return "Index: " + index + ", Size: " + this .size ;
78
+ }
79
+
80
+ private class ArrayListIterator implements Iterator {
81
+
82
+ private int pos = 0 ;
83
+
84
+ public boolean hasNext () {
85
+ return pos != size ;
86
+ }
87
+
88
+ public Object next () {
89
+ int i = pos ;
90
+ if (i >= size )
91
+ throw new NoSuchElementException ();
92
+ Object [] elements = ArrayList .this .elements ;
93
+ if (i >= elements .length )
94
+ throw new ConcurrentModificationException ();
95
+ pos = i + 1 ;
96
+ return (Object ) elements [i ];
97
+ }
98
+ }
99
+
100
+ }
0 commit comments