Fixed index out of bounds exception by checking for empty arraylist