-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathArraylist
More file actions
123 lines (121 loc) · 1.94 KB
/
Arraylist
File metadata and controls
123 lines (121 loc) · 1.94 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
class BoundsException extends Exception
{
void printError()
{
printStackTrace();
System.err.println("Error Occurrred !!");
}
}
interface List
{
public void add(Integer i);
public void traverse();
public void add(Integer p,Integer pos);
}
class ArrayList implements List
{
Integer arr[];
Integer size;
Integer buffer;
ArrayList()
{
buffer=5;//size of array//
size=0;//count of no. of elements//
arr=new Integer[buffer];
}
public void add (Integer i)
{
arr[size]=i;
size++;
if (size==buffer)
{
Integer arr2[]=new Integer [buffer*2];
buffer= buffer*2;
for(Integer y=0;y<size;y++)
{
arr2[y]=arr[y];
}
arr=arr2;
}
}
public void traverse()
{
for(Integer i=0;i<size;i++)
{
System.out.println(arr[i]);
}
}
public void remove(Integer index)
{
for(Integer i=index+1;i<size;i++)
{
arr[i-1]=arr[i];
}
size=size-1;
arr[size]=null;
}
public Integer Binarysearch(Integer a)
{
Integer low=0,mid;
Integer high=size;
while(low<=high)
{
mid=(low+high)/2;
if(arr[mid]<a)
{
low=mid+1;
}
else if(arr[mid]>a)
{
high=mid-1;
}
else
{
return mid;
}
}
public void add(Integer p,Integer pos)
{
try
{
if (pos==-1)
{
throw new BoundsException();
}
}
catch(BoundsException b)
{
b.printError();
return;
}
for(Integer i=size;i>=pos;i--)
{
arr[i]=arr[i-1];
}
arr[pos-1]=p;
size++;
if(size==buffer)
{
Object arr2[]=new Object[buffer*2];
buffer*=2;
for(Integer j=0;j<size;j++)
{
arr2[j]=arr[j];
}
arr=arr2;
}
}
public static void main(String[] args)
{
ArrayList ob=new ArrayList();
for(Integer x=0;x<30;x++)
{
ob.add(x);
}
ob.add(0,-1);
ob.traverse();
ob.remove(5);
ob.traverse();
System.out.println(ob.arr);
}
}