3
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.

Tagir Valeev
  • 97,161
  • 19
  • 222
  • 334
  • It is not making any sense why result is **false** when i used `a` in both `f1` and `f2`. and it become **true** when i use `f2.Set(f1.Get());` – Abu Bakkar Siddique Aug 31 '15 at 09:25

2 Answers2

5

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.

Konstantin Yovkov
  • 62,134
  • 8
  • 100
  • 147
3

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.

akash
  • 22,664
  • 11
  • 59
  • 87