Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 705
Abu Bakkar Siddique Avatar asked Dec 04 '25 02:12

Abu Bakkar Siddique


1 Answers

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.

like image 144
Konstantin Yovkov Avatar answered Dec 06 '25 17:12

Konstantin Yovkov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!