In: Computer Science
Build a simple list implementation that uses arrays to store the values. Create a class SimpleArrayList with a public constructor that initializes the list using a passed array of Object references. Assert that the passed array is not null. Next, implement:
1)Object get(int), which takes an int index and returns the Object at that index
2)void set(int, Object), which takes an int index and an object reference and sets that value at the index to the passed reference
Both your get and set method should assert that index passed is valid for that SimpleArrayList.
Here's an example how your code should work
SimpleArrayList list = new SimpleArrayList(new int[] {1,2,5});
System.out.println(list.get(1)); //prints 2 list.set(1,6);
System.out.println(list.get(1)); //prints 6
System.out.println(list.get(0)); //prints 1
System.out.println(list.get(4)); //generates an assertion error
Note: shouldn't be using java.util.List for the question
Here's the Java Code for the problem asked:
package javaProject;
// generic class SimpleArrayList with template T
class SimpleArrayList<T> {
// private array of type T
private T[] arr;
// constructor
public SimpleArrayList(T[] list) {
assert list != null : "Array is NULL";
arr = list;
}
// getter method
public T get(int index) {
assert (index >= 0 && index < arr.length) : "Index Out of Bounds";
return arr[index];
}
// setter method
public void set(int index, T item) {
assert (index >= 0 && index < arr.length) : "Index Out of Bounds";
arr[index] = item;
}
}
public class ArrayImple {
// driver function
public static void main(String[] args) {
SimpleArrayList<Integer> list = new SimpleArrayList<Integer>(new Integer[] {1, 2, 5});
System.out.println(list.get(1)); //prints 2
list.set(1,6);
System.out.println(list.get(1)); //prints 6
System.out.println(list.get(0)); //prints 1
System.out.println(list.get(4)); //generates an assertion error
}
}
Added comments in the code wherever necessary, do refer them for better understanding! Also, for any doubt, feel free to reach back :)
Sample Output:
Hope it helps, consider hitting a like if it did :)
Cheers!