Commit c3826ab8 authored by Adam Blank's avatar Adam Blank
Browse files

Add new file

parent dda4bfa0
No related merge requests found
Showing with 87 additions and 0 deletions
+87 -0
public class OurArrayList<E> implements IList<E> {
private E[] data;
private int size;
public OurArrayList(int initialCapacity) {
this.data = (E[])new Object[initialCapacity];
this.size = 0;
}
public OurArrayList() {
this(10);
}
public String toString() {
if (this.size == 0) {
return "[]";
}
String result = "[";
for (int i = 0; i < this.size; i++) {
result += this.data[i] + ", ";
}
result = result.substring(0, result.length() - 2);
return result + "]";
}
public void add(E element) {
this.add(this.size, element);
}
/**
* Puts element at index idx, shifting over everything after to the right.
* @param idx
* @param element
* For example, idx = 2, element = 42
* [1, 2, 3, 4, 5]
* ^
* [1, 2, 42, 3, 4, 5]
*/
public void add(int idx, E element) {
resize();
for (int i = this.size; i > idx; i--) {
this.data[i] = this.data[i-1];
}
this.data[idx] = element;
this.size++;
}
private void resize() {
// size vs. capacity < how much storage space in the list
// ^ how many elements in the list
// capacity == this.data.length
if (this.size == this.data.length) {
// Time to resize!
E[] newData = (E[])new Object[this.data.length * 2];
for (int i = 0; i < this.size; i++) {
newData[i] = this.data[i];
}
this.data = newData;
}
}
@Override
public int size() {
return this.size;
}
@Override
public void set(int idx, E elem) {
if (idx < 0 || idx >= this.size) {
throw new IllegalArgumentException(idx + " is not a valid index!");
}
this.data[idx] = elem;
}
public E get(int idx) {
if (idx < 0 || idx >= this.size) {
throw new IllegalArgumentException(idx + " is not a valid index!");
}
return this.data[idx];
}
@Override
public void clear() {
this.size = 0;
}
}
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment