Abu Bakkar Siddique
Abu Bakkar Siddique

Reputation: 159

Strange Logical Error in Java Code

interface New<T> {
   boolean func(T n, T v);
}
class MyFunc<T>{
T val;
MyFunc(T val){
   this.val = val;
}
void Set(T val){
   this.val = val;
}
T Get(){
   return val;
}
boolean isEqual(MyFunc<T> o){
   if(val == o.val) return true;
return false;
}
public class Main {
  static <T> boolean check(New<T> n , T a, T b){
     return n.func(a,b);
  }
  public static void main(String args[]){
   int a = 321;
   MyFunc<Integer> f1 = new MyFunc<Integer>(a);
   MyFunc<Integer> f2 = new MyFunc<Integer>(a);

   boolean result;
   //f2.Set(f1.Get()); //if i uncomment this line result become true
   System.out.println(f1.val + "  " + f2.val);
   System.out.println();

   result = check(MyFunc::isEqual, f1, f2);
   System.out.println("f1 isEqual to f2: " + result);
  }
}

Why result is false when 'a' is used in both f1 and f2? Why result is true when f2.Set(f1.Get()); is uncommented? Please explain me where I am making mistake.

Upvotes: 3

Views: 63

Answers (2)

Akash Thakare
Akash Thakare

Reputation: 23002

a is auto boxed to Integer and for int a = 321; you will have two different Objects for f1 and f2.

FOR EXAMPLE

Integer a1 = new Integer(321);
Integer a2 = new Integer(321);

and for a1 == a2 you will have false because == compare reference instead of value you should use equals method to check value in your isEqual method.

Upvotes: 3

Konstantin Yovkov
Konstantin Yovkov

Reputation: 62874

In the .isEquals() method you're comparing tho wrapper objects with the == operator, which compares the objects references if those are not within the Integer internal cache.

Since 321 is out of the Integer cache, the == operator returns false, because the references are different (f1 refers to different memory address than f2).

When you explicitly set the references to be equal (with f2.Set(f1.Get())), then it's not surprising the program outputs true.

If you set a to something between -128 and 127, the program will output true.

Upvotes: 4

Related Questions