Home > Back-end >  How do i find the duplicates in java array
How do i find the duplicates in java array

Time:10-22

I am trying to make it so if there are any duplicates in the array, it turns true and if there is not it turns false. But, no matter what I do the if statement always turns in into false, even if there isn't a duplicate. This has to be done as a boolean.

 int array[] = {10, 20, 30, 10, 40, 50};

 public boolean hasDuplicates2() {
   for (int i = 0; i <= array.length; i  ) {
     for (int i2 = 1; i2 <= array.length - 1; i2  ) {
       if (array[i] != array[i2]) {
         return false;
       }
     }
   }
   return true;
 }

CodePudding user response:

public static void main(String[] args) {

    int array[] = {10, 20, 30, 10, 40, 50};
    System.out.println(hasDuplicates(array));
}

public static boolean hasDuplicates(int[] array) {
    var distinct = Arrays.stream(array).distinct().count();
    return distinct != array.length;
}

CodePudding user response:

your code return false because its stops when first cycle says its false and after that your for statement return false instead of "return false" you can change a bit

public boolean hasDuplicates2() 
{
  bool hasDuclicates = false;
  for (int i = 0; i <= array.length; i  ) {
   for (int i2 = 1; i2 <= array.length - 1; i2  ) {
    if (array[i] == array[i2]) {
     hasDuplicates = true;
    }
   }
  }
  return hasDuplicates;
}

it may not be efficient by the way

CodePudding user response:

So a couple of problems:

1)You need to have array.length - 1 even in the first for loop, or you're going to go out of range at the last iteration.

2)You're checking each and every element including the element itself - which means when i = i2, you're always going to satisfy the if condition, so you need to check for that as well.

Try this:

public static boolean hasDuplicates2(int[] array) {
    for (int i = 0; i <= array.length - 1; i  ) {
        for (int i2 = 1; i2 <= array.length - 1; i2  ) {
            if (i != i2 && array[i] == array[i2]) {
                return true;
            }
        }
    }
    return false;
}
  • Related