0

I have tried to find index of duplicate elements of 2 in ArrayList - [1, 2, 3, 4, 2, 5, 6, 2, 7, 2].

Which the Output should be [1,4,7,9]. But I am getting as [1,1,1,1]. Please anyone help me in getting the correct output.

package com.practice.first;

import java.util.ArrayList;
import java.util.List;

public class SampleList {

    public static void main(String[] args) {

        List<Integer> al = new ArrayList<Integer>();
        al.add(1);
        al.add(2);
        al.add(3);
        al.add(4);
        al.add(2);
        al.add(5);
        al.add(6);
        al.add(2);
        al.add(7);
        al.add(2);

        for (int i = 0; i < al.size(); i++) {
            if (al.get(i).equals(2)) {
                System.out.println("Element 2 is present at " + al.indexOf(al.get(i)));         
            }
        }

    }
}

2 Answers 2

1

Your problem is in al.indexOf(al.get(i)). From official documentation:

  • get(int index) Returns the element at the specified position in this list.
  • indexOf(Object o) Returns the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element.

You probably want just:

System.out.println("Element 2 is present at " + i);
Sign up to request clarification or add additional context in comments.

Comments

0

From the javadoc of indexOf:

Returns the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element. More formally, returns the lowest index i such that (o==null ? get(i)==null : o.equals(get(i))), or -1 if there is no such index.

So indexOf will always return the first occurence of the element even if it is present multiple times in the list. To get the right index, you just need to print your loop variable i like this:

for (int i = 0; i < al.size(); i++) {
    if (al.get(i).equals(2)) {
        System.out.println("Element 2 is present at " + i);         
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.