Klaven Jones Klaven Jones - 1 month ago 8
Java Question

Java - Is there anyway I can prevent duplicates in an array without using an ArrayList?

I'm trying to create a code to prevent duplicate array elements. Is there anyway I can do this without creating an arrayList?

When running the program this error occurs when I enter the first #:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1
at DuplicateElimination.main(DuplicateElimination.java:32)

Here is my code:

int[] numList = new int[5];
int newValue;
boolean invalid;

for (int i = 0; i < numList.length; i++){
System.out.print("Please enter number");
System.out.println(" ");
newValue = input.nextInt();

//This is where the error occurs when I try to compare
//The last list element to the input value
invalid = numList[i-1] == newValue;

if(newValue < 10 || newValue > 100){
System.out.print("Invalid number, Please enter a number between 10 and 100");
newValue = input.nextInt();
System.out.print("That number was entered already try again");

insertIntoArray(numList, i, newValue);


This answer takes the word for your question title and prevents duplicates without using ArrayList or other collection class. I changed your inner do loop to:

        do {
            System.out.print("Please enter number");
            System.out.println(" ");
            newValue = input.nextInt();

            // See if value was already entered; search all array elements left of index i
            int ix = 0;
            while (ix < i && numList[ix] != newValue) {
            // now either ix == i or numList[ix] == newValue;
            // if ix is not i, it means we encountered a duplicate left of index i
            invalid = ix < i;
            if (invalid) {
                System.out.println("That number was entered already, try again");
            } else if (newValue < 10 || newValue > 100) {
                System.out.println("Invalid number, please enter a number between 10 and 100");
                invalid = true;
        } while (invalid);

This makes sure that the value eventually inserted into numList[i] fulfils both conditions: it’s in the range 10 through 100 and it is not a duplicate. Duplicates are searched among all previously entered values (that is, first time among no values at all since there are no previously entered ones).

It’s not the code I’d recommend for production (rather use a Set), but it’s fine for the exercise.