How to implement your own array list in java

Problem:

Implement your own array list in java.

Output:

Not applicable.

Solution:

import java.util.Arrays;

public class KWArrayList<E>
{
  private static final int INITIAL_CAPACITY = 10;
  
  //Underlying data array
  private E[] theData;
  
  //Current size
  private int size = 0;
  
  //Current Capacity
  private int capacity = 0;
  
  
  @SuppressWarnings("unchecked")
  public KWArrayList()
  {
    capacity = INITIAL_CAPACITY;
    theData = (E[]) new Object[capacity];
  }
  
  public boolean add(E anEntry)
  {
    if (size == capacity)
      reallocate();
    theData[size] = anEntry;
    size++;
    return true;
  }
  
  public void add(int index, E anEntry)
  {
    if (index < 0 || index > size)
      throw new ArrayIndexOutOfBoundsException(index);
    if (size == capacity)
      reallocate();
    
    // Shift data in elements from index to size -1 
    for (int i = size; i > index; i--)
      theData[i] = theData[i - 1];
    
    //Insert the new Item
    theData[index] = anEntry;
    size++; 
  }
  
  public E get(int index)
  {
    if (index < 0 || index >= size)
      throw new ArrayIndexOutOfBoundsException(index);
    
    return theData[index];
  }
  
  public E set(int index, E newValue)
  {
    if (index < 0 || index >= size)
      throw new ArrayIndexOutOfBoundsException(index);
    E oldValue = theData[index];
    theData[index] = newValue;
    return oldValue;
  }
  
  public E remove(int index)
  {
    if (index < 0 || index >= size)
      throw new ArrayIndexOutOfBoundsException(index);
    E returnValue = theData[index];
    
    for(int i = index + 1; i< size;i++)
      theData[i-1] = theData[i];
    size--;
    return returnValue;
  }
  
  
  public int indexOf(Object item) {
    for (int i = 0; i < size; i++) {
    if (theData[i] == null && item == null) {
    return i;
    }
    if (theData[i].equals(item)) {
    return i;
    }
    }
    return -1;
    }
  
  private void reallocate()
  {
    capacity = 2*capacity;
    theData = Arrays.copyOf(theData, capacity);
  }
  
  public int size() {
      return size;
    }
  }
Phone L

No comments:

Post a Comment