MyArrayList - if (size == capacity) reallocate();...

Info iconThis preview shows pages 1–2. Sign up to view the full content.

View Full Document Right Arrow Icon
import java.util.*; i public class MyArrayList <E> { private static final int INITIAL_CAPACITY = 10; private E[] theData; private int size = 0; private int capacity = 0; public MyArrayList() { capacity = INITIAL_CAPACITY; theData = (E[])new Object[capacity]; } public MyArrayList(int capacity) { this.capacity = capacity; theData = (E[])new Object[capacity]; } public void add(int index, E anEntry) { if (index < 0 || index > size) { throw new ArrayIndexOutOfBoundsException(index); } if(size == capacity) reallocate(); for (int i = size; i >= index; i--) { theData[i + 1] = theData[i]; } theData[index] = anEntry; size++; } private void reallocate() { capacity = 2 * capacity; E[] newData = (E[])new Object[capacity]; System.arraycopy(theData, 0, newData, 0, size); theData = newData; } public boolean add(E anEntry) {
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Background image of page 2
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: if (size == capacity) reallocate(); theData[size] = anEntry; size++; return true; } public E get(int index) { if (index &lt; 0 || index &gt;= size) { throw new ArrayIndexOutOfBoundsException(index); } return theData[index]; } public E set(int index, E newValue) { if (index &lt; 0 || index &gt;= size) { throw new ArrayIndexOutOfBoundsException(index); } E oldValue = theData[index]; theData[index] = newValue; return oldValue; } public E remove(int index) { if (index &lt; 0 || index &gt;= size) { throw new ArrayIndexOutOfBoundsException(index); } E returnValue = theData[index]; for (int i = index + 1; i &lt; size; i++) { theData[i - 1] = theData[i]; } size--; return returnValue; } public int size() { return size; } }...
View Full Document

Page1 / 2

MyArrayList - if (size == capacity) reallocate();...

This preview shows document pages 1 - 2. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online