From c3826ab8cf38c834e9ef1606e44990bcae5156f1 Mon Sep 17 00:00:00 2001 From: Adam Blank <blank@caltech.edu> Date: Fri, 14 Jan 2022 17:33:37 +0000 Subject: [PATCH] Add new file --- 04/OurArrayIntList.java | 87 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 87 insertions(+) create mode 100644 04/OurArrayIntList.java diff --git a/04/OurArrayIntList.java b/04/OurArrayIntList.java new file mode 100644 index 0000000..60ded47 --- /dev/null +++ b/04/OurArrayIntList.java @@ -0,0 +1,87 @@ +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; + } +} -- GitLab