-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathDynamicArray.java
87 lines (84 loc) · 1.62 KB
/
DynamicArray.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
package DataStructure;
import java.util.Arrays;
class DynamicArray<T>
{
private T array[];
private int capacity;
private int size;
@SuppressWarnings("unchecked")
public DynamicArray()
{
// TODO Auto-generated constructor stub
capacity=10;
setArray((T[])new Object[capacity]);
setSize(0);
}
private void setSize(int i)
{
// TODO Auto-generated method stub
size=i;
}
private void setArray(T[] ts)
{
// TODO Auto-generated method stub
array=ts;
}
@SuppressWarnings("unchecked")
public DynamicArray(int capacity)
{
this.capacity=capacity;
setArray((T[])new Object[capacity]);
setSize(0);
}
public int getSize()
{
return size;
}
public T get(int index)
{
if(index>=size)
throw new IllegalStateException("Index Illegal");
else
return array[index];
}
private void ensureExtraCapacity()
{
if(size==capacity)
{
capacity<<=1;
setArray(Arrays.copyOf(array, capacity));
}
}
public void add(T value)
{
ensureExtraCapacity();
array[size++]=value;
}
public boolean contains(T value)
{
for(int i=0;i<size;i++)
{
if(array[i].equals(value))
return true;
}
return false;
}
public T[] getArray()
{
return Arrays.copyOf(array, size);
}
public String toString()
{
if(size==0)
return "[]";
else
{
StringBuilder buffer=new StringBuilder();
buffer.append("[");
for(int i=0;i<size-1;i++)
buffer.append(array[i].toString()+", ");
buffer.append(array[size-1].toString()+" ]");
return buffer.toString();
}
}
}