Skip to content

Instantly share code, notes, and snippets.

@khayyamsaleem
Created September 8, 2017 15:07
Show Gist options
  • Save khayyamsaleem/a18bfd41e521698e4fbe38e4f43ba5d8 to your computer and use it in GitHub Desktop.
Save khayyamsaleem/a18bfd41e521698e4fbe38e4f43ba5d8 to your computer and use it in GitHub Desktop.
package rc2;
/**
*
* @author khayyamsaleem A class that creates an interface for an array
* @param <E>
* generic parameter
*/
public class MyArray<E> {
private E[] data;
private int size;
private int cur = 0;
private static class Node<E> {
E data;
int num;
public Node(E data, int num) {
this.data = data;
this.num = num;
}
public String toString() {
return "(" + data.toString() + ", " + num + ")";
}
}
/**
* Constructor for the MyArray class
*
* @param size
* the fixed size of the array
*/
@SuppressWarnings("unchecked")
public MyArray(int size) {
this.size = size;
this.data = (E[]) new Object[size];
}
/**
* a get method for our array
*
* @param index
* index of item to retrieve
* @return item at given index
*/
public E get(int index) {
if (index < 0 || index >= this.size) {
throw new IndexOutOfBoundsException();
}
return this.data[index];
}
/**
* adds an element to our array
*
* @param elem
* element to add
*/
public void add(E elem) {
if (this.cur >= this.size) {
throw new IndexOutOfBoundsException();
}
this.data[cur] = elem;
this.cur++;
}
/**
* overloads other add function, allows to add at index
*
* @param elem
* element to add
* @param index
* index at which to add
*/
public void add(E elem, int index) {
if (index < 0 || index >= this.size) {
throw new IllegalArgumentException();
}
this.data[index] = elem;
}
/**
* removes item at given index
*
* @param index
* index at which to remove item
* @return item that was removed
*/
public E remove(int index) {
if (index < 0 || index >= this.size) {
throw new IllegalArgumentException();
}
E item = this.data[index];
this.data[index] = null;
return item;
}
/**
* tostring function for our array
*
* @return string representation of the array
*/
public String toString() {
String out = "";
out += "[ ";
for (int i = 0; i < this.size; i++) {
if (this.get(i) == null) {
out += "null ";
} else {
out += this.get(i) + " ";
}
}
out += "]";
return out;
}
public static void main(String[] args) {
MyArray<String> s = new MyArray<String>(5);
s.add("Hello");
s.add("Shalom");
s.add("Hola", 4);
System.out.println(s);
s.remove(1);
System.out.println(s);
MyArray<Node<Boolean>> evens = new MyArray<Node<Boolean>>(10);
for (int i = 0; i < 10; i++) {
evens.add(new Node<Boolean>(i%2==0, i));
}
System.out.println(evens);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment