Trying to get index values of an ArrayList and add them to another ArrayList

Maybe somebody could help me. I don’t understand what is wrong with my code.

I want loop through the ArrayList, get the index value of each element (index number itself) and add these index values to another array. Don’t ask me why =))

Here’s my code:

List<Integer> a = new ArrayList<>();

List<Integer> b = new ArrayList<>();

for (int i = 0; i < a.size(); i++) {



System.out.println("array b: " + b);

Output: array b: [-1, 2, 0]

But my expected output is: [0, 1, 2]

Maybe it’s a very simple question but I’m really stuck and don’t understand why the output is so strange.

>Solution :

Because in your code you are checking what index of the element

like you define loop will iterate 3 time with
i=0, i=1 and i =2

when i =0, there are no such element 0 in your array list it has only 2, 5, 1
so it is returning -1

when i = 1 you have an element, so it is returning the value of the index that’s 2

when i = 2 again you have an element in array list, so it is returning an index of 2 that’s 2

what you can do is

b.add(a.indexOf(i)); replace this line with b.add(a.indexOf(a.get(i)));

but that simply means adding i to new list

Leave a Reply