Anyway, I have this extremely simple java program to find out if 2 objects in an array are the same. How ever when I run it when a set of unique objects it always returns 1 error, If I add more objects that are the same it counts as normal.
This is the code;
int[] array= new int[] {1,245,324,523};
int size = array.length;
int error=0;
System.out.println(error);
int i = 0;
for(i=0; i<size; i++){
if(array[0] == array[i]){
error= error +1;
}
System.out.println(error);
}
The 1 error is because you’re comparing
array[0]witharray[0], which is of course equal to itself.If you want to find all pairwise duplicates, you will need to do a double loop:
You’ll notice a few things from this code:
erroris only incremented when i!=jThe first is because you’re taking turns with each element in your array to compare with every other element. By the time its turn comes around (in the outer loop), it’s already been compared to the elements before it, and should not be compared with them again.
The second is because you’ll end up comparing an element to itself for each outer loop. You don’t want to count it as an
error.