I'm trying to find a way to find, and remove, duplicates in an ArrayList without using sets or hashes. This is what I have so far, but I keep getting the following error:
import java.util.*;
public class Duplicates
{
Scanner input = new Scanner( System.in );
int i;
ArrayList<Integer> numbers = new ArrayList<Integer>(5);
public void EnterNumbers()
{
System.out.println("Please Enter 5 variables: ");
for (i=0; i<5; i++)
{
System.out.printf("Please enter value in slot " + i + ":");
numbers.add(input.nextInt());
}
System.out.println("ArrayList Values Are: " + numbers );
for ( int j=0; j<=numbers.size(); j++)
{
if ( numbers.get(i).equals(numbers.get(j)))
{
numbers.remove(j);
}
}
System.out.println("ArrayList Values Are: " + numbers );
}
public static void main(String[] args)
{
Duplicates DuplicateTest = new Duplicates();
DuplicateTest.EnterNumbers();
}
}
Error:
Please Enter 5 variables:
Please enter value in slot 0:5
Please enter value in slot 1:4
Please enter value in slot 2:3
Please enter value in slot 3:2
Please enter value in slot 4:1
ArrayList Values Are: [5, 4, 3, 2, 1]
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 5, Size: 5
at java.util.ArrayList.RangeCheck(Unknown Source)
at java.util.ArrayList.get(Unknown Source)
at Duplicates.EnterNumbers(Duplicates.java:26)
at Duplicates.main(Duplicates.java:39)