You are on page 1of 2

class Array { Integer a[] ; int size; Array(int n) { if(n<1) throw new IllegalArgumentException("size of the array should be >=1");

a = new Integer[n]; size = 0; } public boolean isEmpty(){ return size == 0; } public int size(){ return size; } public void checkIndex(int index){ if(index < 0 index >= a.length) throw new IndexOutOfBoundsException("index = "+index+" size = "+ size); } public Integer get(int index){ checkIndex(index); return a[index]; } public int indexOf(Integer x){ for (int i = 0; i < a.length; i++) if(a[i] == x) return i; return -1; } public void add(int index, Integer x){ checkIndex(index); if(size() == a.length){ System.out.println("Array is Full, action is aborted"); return ; } if(a[index] != null) for(int i = size-1; i >= index; i--) if(a[i+1] == null){ a[i+1] = a[i]; a[i]=null; } a[index] = x; size++; } public Integer del(int index){ checkIndex(index); int deleted = a[index];

for(int i = index + 1; i < size(); i++) a[i - 1] = a[i]; a[--size] = null; return deleted; } public String toString(){ StringBuffer s = new StringBuffer("["); for(int i = 0; i < a.length; i++) if(a[i] == null) s.append("null, "); else s.append(a[i]+", "); if(a.length > 0) s.delete(s.length()-2, s.length()); s.append("]"); return new String(s); } } public class DemoArray{ public static void main (String[] args) { Array Ar = new Array(8); Ar.add(0,25); System.out.println(Ar); Ar.add(7,45); System.out.println(Ar); Ar.add(6,50); System.out.println(Ar); Ar.add(5,33); System.out.println(Ar); Ar.add(5,99); System.out.println(Ar); // Ar.add(2,76); // System.out.println(Ar); // Ar.del(3); // Ar.add(4,90); // System.out.println(Ar); // Ar.add(2,25); // System.out.println(Ar.indexOf(33)); } }

You might also like