Search code examples
javaarraylistindexoutofboundsexception

Getting an IndexoutofboundException while using an ArrayList


Given a list of numbers, such that all but one element occurs more than once in the list. Find the element that occurs only once.

This is Java implementation:

package competitiveprograming;
import java.util.*;

public class FindSingleInArray {

    public static void main(String[] args) {
        Scanner sc= new Scanner(System.in);
        System.out.print("Enter size of array");
        int size=sc.nextInt();
        System.out.print("Enter an element where one of the element will not repeat again..");
        int arr[]= new int[10];
        for(int i=0;i<size;i++)
        {
            arr[i]=sc.nextInt();
        }

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

        for(int j : arr)
        {
            if(!no_duplicate_list.contains(j))
            {
                no_duplicate_list.add(j);
            }
            else
            {
                no_duplicate_list.remove(j);
            }
        }

        System.out.print(no_duplicate_list.get(0));
        sc.close();
    }
}

And this is the error message I'm getting:

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index 2 out of bounds for length 1
    at java.base/jdk.internal.util.Preconditions.outOfBounds(Preconditions.java:64)
    at java.base/jdk.internal.util.Preconditions.outOfBoundsCheckIndex(Preconditions.java:70)
    at java.base/jdk.internal.util.Preconditions.checkIndex(Preconditions.java:248)
    at java.base/java.util.Objects.checkIndex(Objects.java:373)
    at java.base/java.util.ArrayList.remove(ArrayList.java:502)
    at competitiveprograming/competitiveprograming.FindSingleInArray.main(FindSingleInArray.java:28)

Solution

  • If I understand you correctly, you are trying to find all elements in the input array which were NOT repeated.

    So if this is the input array:

    1 2 2 3 3 3 4
    

    The output should look like this:

    1 4
    

    But your code will produce this because every uneven time the number appears it will add it to the no_duplicate_list again:

    1 3 4
    

    This is however not the reason for your exception. The reason for the exception is because you are passing an int j to List.remove(int position) and it tries to remove the element at position j, and not the element with value of j. To fix this you need to cast your int into Integer before removing it from the list, this way you are calling List.remove(Integer object).

    no_duplicate_list.remove((Integer)j);