Question
public class ArrayList > implements List { private boolean isSorted; T[] a; private int noOfElements; @SuppressWarnings(unchecked) public ArrayList() { noOfElements = 0; a = (T[])
public class ArrayList
{
private boolean isSorted;
T[] a;
private int noOfElements;
@SuppressWarnings("unchecked")
public ArrayList()
{
noOfElements = 0;
a = (T[]) new Comparable[2];
isSorted = true;
}
@Override
public boolean add(T element) {
if(element==null)
return false;
else
{
int i=0;
while(a[i] != null && i
i++;
if(a[i] == null)
a[i] = element;
else if(i == a.length)
{
a = newArray();
a[i] = element;
noOfElements++;
}
isSorted = false;
return true;
}
}
@Override
public boolean add(int index, T element) {
if(element == null)
return false;
else
{
if(index = a.length) // index out of bounds
return false;
if(a[index] == null)
a[index] = element;
else
{
int i;
if(a[size() - 1] != null) // if last element is not null, means array is full
{
a = newArray();
i = size()/2;
}
else
i = noOfElements - 1;
while(i != index)
{
a[i] = a[i-1];
i--;
}
a[i] = element;
noOfElements++;
}
isSorted = false;
return true;
}
}
@Override
public void clear() {
for(int i = 0 ; i
a[i] = null;
noOfElements = 0;
}
@Override
public boolean contains(T element) {
for(int i=0;i if(a[i]==element) return true; return false; } @Override public T get(int index) { if(index = a.length) return null; else return a[index]; } @Override public int indexOf(T element) { for(int i=0;i if(a[i]==element) return i; return -1; } @Override public boolean isEmpty() { if(noOfElements == 0) return true; return false; } @Override public int lastIndexOf(T element) { for(int i = noOfElements-1 ; i >= 0 ; i--) if(a[i] == element) return i; return -1; } @Override public T set(int index, T element) { if(element == null || index = a.length) return null; T temp = a[index]; a[index] = element; return temp; } @Override public int size() { return noOfElements; } @Override public void sort(boolean order) { if(!isSorted) { if(order) // ascending { } else // descending { } } else { if(!order) // descending { } } } @Override public boolean remove(T element) { int i=0; while(i { if(a[i] == element) { int j = i; while(j { a[j] = a[j+1]; j++; } return true; } i++; } return false; } @Override public T remove(int index) { if(index = a.length) return null; T temp = a[index]; int i=0; while(i { if(i == index) { int j = i; while(j { a[j] = a[j+1]; j++; } return temp; } } return null; } @SuppressWarnings("unchecked") private T[] newArray() { int size = 2*a.length; T[] array = (T[])new Comparable[size]; for(int i=0;i array[i] = a[i]; return array; }
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started