-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCreateArrayList.java
More file actions
123 lines (105 loc) · 2.12 KB
/
CreateArrayList.java
File metadata and controls
123 lines (105 loc) · 2.12 KB
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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
public class CreateArrayList<T> {
T data[];
int size;
CreateArrayList()
{
this(1);
}
CreateArrayList(int inicap) {
if(inicap>0)
data=(T[]) new Object[inicap];
else if(inicap==0)
data=(T[]) new Object[0];
else
throw new IllegalArgumentException("Capacity cannot be negative");
}
public void add(T value)
{
ensureCapacity();
data[size]=value;
size++;
}
public void ensureCapacity() {
if(data.length<=size)
{
int oldcap=data.length;
int newcap=oldcap+1;
T temp[];
temp=(T[]) new Object[newcap];
for (int i = 0; i < data.length; i++) {
temp[i]=data[i];
}
data=temp;
}
}
public void add(int index,T element)
{
if(index>size || index<0)
throw new ArrayIndexOutOfBoundsException();
ensureCapacity();
for (int i = size-1; i >=index; i--) {
data[i+1]=data[i];
}
data[index]=element;
size++;
}
public T get(int index)
{
if(index>size || index<0)
throw new ArrayIndexOutOfBoundsException();
return data[index];
}
public void remove(int index)
{
if(index>size || index<0)
throw new ArrayIndexOutOfBoundsException();
for (int i = index; i < data.length-1; i++) {
data[i]=data[i+1];
}
size--;
T temp[];
temp=(T[]) new Object[size];
for (int i = 0; i < temp.length; i++) {
temp[i]=data[i];
}
data=temp;
}
public int indexof(T element)
{
for (int i = 0; i < data.length; i++) {
if(data[i]==element)
{
return i;
}
}
return -1;
}
public boolean contains(T value)
{
if(indexof(value)!=-1)
return true;
else
return false;
}
public String toString()
{
for (int i = 0; i < data.length; i++) {
System.out.print(data[i]+"\t");
}
System.out.println();
return "";
}
public static void main(String[] args) {
CreateArrayList<Integer> c=new CreateArrayList();
c.add(5);
c.add(2);
c.add(6);
c.add(9);
System.out.println(c);
/*c.add(2, 7);
System.out.println(c);
c.remove(2);
System.out.println(c);*/
System.out.println(c.indexof(7));
}
}