Skip to content

Instantly share code, notes, and snippets.

@kjlubick
Created April 9, 2015 23:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kjlubick/2e5834394b2da9e1ab53 to your computer and use it in GitHub Desktop.
Save kjlubick/2e5834394b2da9e1ab53 to your computer and use it in GitHub Desktop.
String ArrayList. Targeted at AP Computer Science Students. Used with https://www.youtube.com/watch?v=JcTA3grnERo
public class ArrayListString{
private String[] arr;
private int capacity;
private int size;
public ArrayListString() {
arr = new String[10];
capacity = 10;
size = 0;
}
public boolean add(String str)
{
if (capacity <= size) {
resize(capacity * 2);
capacity = capacity * 2;
}
arr[size] = str;
size++;
return true;
}
private void resize(int newCapacity)
{
//Create a new String array with newCapacity elements
String[] newArr = new String[newCapacity];
//Copy all of the old elements into this new array
for(int counter = 0;counter<capacity;counter++) {
newArr[counter] = arr[counter];
}
//Change field (arr) to reference new array
arr = newArr;
}
public int size() {
return size;
}
public void add(int index, String str) {
//check if capacity is good. If not, expand
if (capacity <= size) {
resize(capacity * 2);
capacity = capacity * 2;
}
//move items at index, index+1...end of list to the right.
for(int counter = size-1;counter>=index;counter--) {
arr[counter+1] = arr[counter];
}
//Add our item
arr[index] = str;
size++;
}
public String get(int index) {
if (index >= 0 && index<size) {
return arr[index];
}
System.out.println("Out of range");
return null;
}
public void set(int index, String str) {
if (index >= 0 && index < size) {
arr[index] = str;
return;
}
System.out.println("Out of range");
}
public String remove(int index) {
//Make a local that holds onto the element we remove
String temp = arr[index];
//Move all elements index+1, index+2 ... one index to the left
for(int counter = index;counter<size-1;counter++) {
arr[counter] = arr[counter+1];
}
size--;
//return removedElement
return temp;
}
}
public class Runner
{
public static void main(String[] args) {
ArrayListString list = new ArrayListString();
boolean didAdd = list.add("Hello,");
didAdd = didAdd && list.add("World!");
System.out.println("Both items added: "+didAdd);
System.out.println("Should be 2 : "+list.size());
for(int i = 0;i<20;i++) {
list.add("!");
}
System.out.println("Should be 22 : "+list.size());
//add to middle
list.add(1, "Middle");
System.out.println("Should be 23 : "+list.size());
System.out.println("SHould be World! "+list.get(2));
list.set(0, "Goodbye");
System.out.println("Should be Goodbye "+list.get(0));
String removedValue = list.remove(1);
System.out.println("Removed "+removedValue);
//System.out.println(list);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment