-
Notifications
You must be signed in to change notification settings - Fork 2
/
pavan_dynamic_array.java
83 lines (72 loc) · 2.05 KB
/
pavan_dynamic_array.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
import java.io.Serializable;
public class pavan_dynamic_array implements Serializable {
private Object[] array;
private int size;
public pavan_dynamic_array(int initialCapacity) {
array = new Object[initialCapacity];
size = 0;
}
private void resizeArray() {
int newCapacity = Math.max(size * 2, 1);
Object[] newArray = new Object[newCapacity];
for (int i = 0; i < size; i++) {
newArray[i] = array[i];
}
array = newArray;
}
public void add(Object item) {
if (size == array.length) {
resizeArray();
}
array[size++] = item;
}
public void remove(Object item) {
int index = indexOf(item);
if (index != -1) {
for (int i = index; i < size - 1; i++) {
array[i] = array[i + 1];
}
size--;
}
}
public int indexOf(Object element) {
for (int i = 0; i < size; i++) {
if (array[i].equals(element)) {
return i;
}
}
return -1;
}
public int size() {
return size;
}
public Object get(int index) {
if (index >= 0 && index < size) {
return array[index];
}
return null;
}
public Object[] getArray() {
Object[] newArray = new Object[size];
for (int i = 0; i < size; i++) {
newArray[i] = array[i];
}
return newArray;
}
public void addAll(pavan_dynamic_array otherArray) {
if (size + otherArray.size() > array.length) {
int newCapacity = Math.max(size + otherArray.size(), array.length * 2);
Object[] newArray = new Object[newCapacity];
for (int i = 0; i < size; i++) {
newArray[i] = array[i];
}
array = newArray;
}
for (int i = 0; i < otherArray.size(); i++) {
add(otherArray.get(i));
}
}
public boolean contains(Object item) {
return indexOf(item) != -1;
}
}