I'm trying to add elements into Arraylist using non-continuous indexes, for example:
I want to add an element at index 3 first before adding any element at indexes (0,1,2). I will also fill up the indexes at 0,1,2 later.
Here's my code:
public static void main(String[] args) throws FileNotFoundException {
List<Integer> numbers= new ArrayList<Integer>();
Scanner inp = new Scanner(System.in);
int[] x = {1,5,2,4,3,0};
System.out.println("Enter elements:"+"\n");
for(int i=0;i<x.length;i++) {
int index = x[i];
numbers.add(index, inp.nextInt());
}
I seem to get this error:
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 1, Size: 0
at java.util.ArrayList.rangeCheckForAdd(Unknown Source)
at java.util.ArrayList.add(Unknown Source)
at Test1.main(Test1.java:28)
I understand the error, but I don't seem to find a way out of this problem. Any help will be much appreciated. If at all there's another fancy data structure which allows me to do non-continuous indexing please let me know, excuse me if my questions doesn't make any sense.