Reputation: 27
After sorting an integer array "arr"
I try to identify duplicates in the array. It does that for part of the array, but it does not identify duplicates in the whole array. I appreciate the help. Here is my code:
import java.util.*;
public class Ex24 {
public static void main(String[] args) {
int i, n = 100;
Integer[] arr = Collections.nCopies(n, 0).toArray(new Integer[0]);
// int[] array = {0};
for (int j = 0; j < n ; j++){
arr[j] = (int) (Math.random() * 365 + 1);
// System.out.print(j + " " + arr[j] + "\n");
}
Arrays.sort(arr); //sort the arr
// String arrq = (Arrays.toString(arr));
System.out.println("\n");
Duplicate(arr, n);
}
static void Duplicate(Integer[] arr, int n) {
int j = 0;
for (int i = 0; i < n-1 ; i++) {
if (arr[i] != arr[i+1]) {
System.out.println(" at i (" + i + ") print arr[i] " + arr[i]);
}
else {
j = j +1;
System.out.println(" j = " + j + " at i (" + i + ") arr[i] is double at date " + arr[i]);
}
}
}
}
Upvotes: 0
Views: 98
Reputation: 2790
You comparing objects with ==
what is wrong.
if (arr[i] != arr[i+1]) {
Two ways to fix this particular issue with Integer:
1 .
if (!arr[i].equals(arr[i+1])) {
2 .
if (arr[i].intValue() != arr[i+1].intValue()) {
Upvotes: 0
Reputation: 1500385
The problem is that you're comparing Integer
references using ==
. (Or rather, !=
.)
The ==
and !=
operators will always compare references when the operands are reference type expressions - they compare whether the two operands are references to the exact same object, rather than whether they refer to equal objects.
Boxing in Java is guaranteed to use a cache of Integer
objects for values in the range -127 to 127 which is why you're seeing it work for some values. Beyond that (or some point1) you'll be seeing different Integer
objects which won't compare as equal when simply compared by reference. You want to compare for value equality instead, with the equals
method:
if (!arr[i].equals(arr[i+1]))
1 The exact boundary is implementation-specific: some implementations may have a larger cache.
Upvotes: 0
Reputation: 785098
Since you're comparing Integer Objects so instead of:
if (arr[i] != arr[i+1])
do this:
if (!arr[i].equals(arr[i+1]))
Pls understand that !=
or ==
operators are used for comparing primitives or for comparing Object references instead of comparing actual Object values.
btw your code needs some refactoring. If you really want to find duplicates there are some better ways to do that like using java.util.Set
instead of Sorting the array to find duplicates.
Upvotes: 1