简体   繁体   中英

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++){
    do{
        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();
        }
        if(invalid){
            System.out.print("That number was entered already try again");
        }
    }while(invalid);

    insertIntoArray(numList, i, newValue);
    printArray(numList);
}

You prevent duplicates in collections by

  1. Using classes that have reasonable equals methods
  2. then using Sets ; because those, by their very nature prevent you from "collecting" duplicates

The other way is: before adding a new element; you simply iterate your complete existing array to see if it already contains the to-be-added thingy. And if so, your code kindly refuses to add the already known "new" element.

In essence: you definitely do not need a "second" ArrayList to do that. If the whole point of your application is to "collect" certain objects, without duplicates, then you just use a Set. You simply kick out the array; and you just use a Set.

There is one more way using "Arrays" class binarySearch method.

The binarySearch method accepts the array and key to be searched on the array and returns index if the key is found.

The array input should be in the sorted order. You can use Arrays.sort to sort the array and use it as input.

Example:

int index = Arrays.binarySearch(Arrays.sort(inputArray), key);

If the key is found, don't add the value to array. Otherwise, add the value to array.

Your code is good only these initiating the matrix out of position, here:

invalid = numList[i-1] == newValue;

Try this :

invalid = numList[i] == newValue;

If you want to prevent duplicate elements, HashSet is a good option.

In arrays, you will need something to track the elements for repetition. HashSet will do it for you in O(1) time complexity.

Using HashSet.contains(Object) , you can check if an element already exists. Using HashSet.toArray(T[]) , you can obtain array in last.

Regarding java.lang.ArrayIndexOutOfBounds , your iteration variable starts from 0, so:

if i = 0; numList[i-1] = numList[-1]

which is an invalid index because array indices starts from 0. So, either change is to numList[i] or change loop to for(int i = 1; i <= numList.length; i++) .

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) {
                ix++;
            }
            // 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM