ITCS214
Completed
[CODE] KWArrayList.java
/* /////////////////////////////////////////// Prepared by: OL Academy Whatsapp: 66939059 Instagram: olearninga Website: www.olearninga.com /////////////////////////////////////////// */ import java.util.ArrayList; import java.util.Arrays; public class KWArrayList <E>{ //Data fields private static final int INITIAL_CAPACITY = 10; // The default initial capacity private E[] theData; // The underlying data array private int size ; // The current size private int capacity ; // The current capacity //default constructor public KWArrayList() { capacity = INITIAL_CAPACITY; size = 0; theData = (E[]) new Object[capacity]; } //constructor with parameter public KWArrayList(int cap) { capacity = cap; size = 0; theData = (E[]) new Object[capacity]; } public int size(){return size;} public int getsize(){return size;} private void reallocate() { capacity *= 2; theData= Arrays.copyOf(theData,capacity); } public boolean isEmpty() { return size==0; } public boolean add(E item) { if(size == capacity) reallocate(); theData[size] = item; size++; return true; } public void add(int index, E item) { if (index<0 || index >size) throw new ArrayIndexOutOfBoundsException(index); if(size == capacity) reallocate(); for(int i = size; i>index; i--) //shift elements to the right theData[i] = theData[i-1]; theData[index] = item; size ++; } public E get(int index) { if(index<0 || index>size) throw new ArrayIndexOutOfBoundsException(index); return theData[index]; } public E set(int index, E item) { if(index <0 || index >= size) throw new ArrayIndexOutOfBoundsException(index); E oldValue = theData[index]; theData[index] = item; return oldValue; } public int indexOf(E item) { for(int i=0; i<size; i++) if(theData[i].equals(item)) return i; return -1; } public boolean contains(E item) { for(int i=0; i<size; i++) if(theData[i].equals(item)) return true; return false; } public E remove(int index) { if(index <0 || index >= size) throw new ArrayIndexOutOfBoundsException(index); E deleted = theData[index]; for(int i=index+1; i<size; i++) theData[i-1]= theData[i]; size--; return deleted; } public boolean remove(E item) { int index = indexOf(item); if (index != -1) { remove(index); return true; } else return false; } public void clear() { for(int i=0; i<size; i++) theData[i] = null; size = 0; } public String toString() { String str ="["; for (int i=0; i<size; i++){ if (i==size-1) str += theData[i]; else str += theData[i]+ ", "; } return str + "]"; } }
Rating
0
0
There are no comments for now.