Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

List<Integer> a = new ArrayList<>();
a.add(2);
a.add(5);
a.add(1);

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

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

    b.add(a.indexOf(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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading