I'm trying to count how many numbers that I want an array has. That is, if I ask it to count the number of fours, it returns the number of fours in the array. When I do the test, it gives me the number of the variable contador
as if it had not been counted in the loop for
. I imagine it's silly but I've tried several ways and the exercise doesn't work.
Thanks in advance I attach the code here:
public static int contador(Integer[] a, Integer elem) {
// Hay que modificar este metodo
int contador= 0;
for(int i =0 ; i<a.length;i++) {
if(a[i]== elem) {
contador++;
}
}
return contador;
}
I am afraid that by doing
You are comparing objects and not the contents of the objects. You are checking if the reference to the object in
a[i]
is the same aselem
and obviously they are different objects (instances), so the condition will never be met and the counter will remain zero.What you have to do is compare the integer value of the object and you can do that in several ways. For example:
You compare the integer values of each of the objects.
To compare this type of elements you must use the equals function, if you use == you are comparing the memory address.
The substantial difference is that, in JAVA, int is a primitive type, not an object, while Integer is an object or a Class.
Said in colloquial language: an int is a number, and an Integer is a pointer that refers to a class that contains an integer. Or... more colloquially: an Integer is a box, and an int is what's inside that box.
The code is fine, maybe your error is in the parameters that you are passing when you call the function