I have two classes, RandomObtainableList<E>
and Driver
. RandomObtainableList extends ArrayList and implements RandomObtainable (which contains only 2 abstract methods) and implements the methods.
However when I run the Driver class it says that there is a NullPointerException on the second line of the main method in the Diver class (Integer i = ...). I can't work out why it's throwing this exception as both classes look fine to me.
public class RandomObtainableList<E> extends ArrayList<E> implements RandomObtainable<E> {
private Random random;
public RandomObtainableList() {
super();
random = new Random();
}
@Override
public E getRandom() throws NoSuchElementException {
//returns an element randomly selected from the collection
E e = this.get(random.nextInt(this.size()));
return e;
}
@Override
public boolean removeRandom() throws UnsupportedOperationException {
//try to remove a random element from the collection
boolean b = false;
int size = this.size();
if (size != 0){
E e = this.remove(random.nextInt(this.size()));
b = true;
}
return b;
}
}
And Driver
class
public class Driver {
public static RandomObtainableList<Integer> list;
public void Driver(){
list = new RandomObtainableList<>();
list.add(1);
list.add(2);
}
public static void main(String[] args){
Driver d = new Driver();
Integer i = list.getRandom();
boolean b = list.removeRandom();
System.out.println("Element retrieved: " +i);
System.out.println("Element removed: " +b);
}
}