I cannot see anything wrong with my code:-
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
int[] A = new int[] {2, 1, 1, 2, 3, 1};
ArrayList<Integer> foundNumbers = new ArrayList<>();
int distinct = 0;
for(int i = 0; i < A.length-1; i++) {
if(foundNumbers.get(i-1) == null) {
foundNumbers.set((i-1), A[i]);
distinct++;
}
}
System.out.println(distinct);
}
}
I want to check if the value of Array element i has already been assigned to ArrayList element i-1, then increment the distinct variable and print how many distinct values are in the array.
Here's the exception when I change the value of i to 1:-
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at java.util.ArrayList.rangeCheck(ArrayList.java:604)
at java.util.ArrayList.get(ArrayList.java:382)
at tdd.Main.main(Main.java:19)