EpimKrit
EpimKrit

Reputation: 13

Not able to find element in an Integer array

In this code, I am able to find and count any element that's less than 10. But when it comes to finding an element that is greater than 10 the counter always shows 0, even though the searched element is present in an array. I used generic interface and static methods... Word counting is working properly, but the problem is with numbers greater than 10, it always shows 0. Here is the code:

 interface FuncCounter<T>{
    int function(T[] t, T tt);
}
class Implementation{
    static<T> int equalValues(T[] t , T tt) {
        int counter = 0;
        for(int i = 0 ; i< t.length; i++) {
            if(t[i]==tt)
                counter++;
        }
        return counter;
    }
}

public class GenericMethodRef{
    static<T> int countOperation(funcCounter<T> fc , T[] t , T v) {
        return (int) fc.function(t, v);
        
    }
    public static void main(String []args) {
        Integer[] nums = {1,1,2,3,4,4,5,6122,23,4,12,44,12,12,12,44,5,6,32, 318,318,318};
        String[] words = {"one","two","three","four","four","twelve","eleven", "eleven"};
        int countNum = countOperation(Implementation::<Integer>equalValues,nums,6122);
        int countWords = countOperation(Implementation::<String>equalValues,words,"eleven");
        System.out.println("318 presence: " + countNum);
        System.out.println("'eleven' counted: " + countWords);
        
    }```

Upvotes: 0

Views: 54

Answers (3)

Axel
Axel

Reputation: 14159

Even if your method is called equalValues, you don’t use the equals() method, and that’s the problem: you pass an array of Integer, the wrapper class for it. Objects for values smaller than an implementation defined limit are cached, so it works for small numbers. Larger values are not held in the cache and so the identity operator == returns false.

You can fix your code by using Objects.equals(t[i], tt) instead.

Please read up on the difference between == and equals in the Java documentation for more details.

Upvotes: 0

Lovesh Dongre
Lovesh Dongre

Reputation: 1344

Remember these 3 rules

  1. == on primitive data type will compare the actual values
  2. == on reference data type will compare whether the two objects share the same memory or not
  3. equals() method for predefined class will compare the actual values for reference datatype. It can be overridden for our own classes.

Upvotes: 0

JayC667
JayC667

Reputation: 2576

This is because you use AutoBoxing on Integers, which turn int into Integer, and as a reference it will not properly work with the == operator.

Instead, use the .equals() method, or better yet, the Objects.equals(t[i], tt) call.

To add, Integers and Longs and even Strings etc are usually (in most JVMs) stored/hashed for int values from -10 to 10 to point to the IDENTICAL objects (== works). So this is why it wrongly works on low numbers but fails on higher numbers.

Upvotes: 2

Related Questions