lambda - 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 = 321;    myfunc<integer> f1 = new myfunc<integer>(a);    myfunc<integer> f2 = new myfunc<integer>(a);     boolean result;    //f2.set(f1.get()); //if uncomment 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 f2: " + result);   } } 

why result false when 'a' used in both f1 , f2? why result true when f2.set(f1.get()); uncommented? please explain me making mistake.

in .isequals() method you're comparing tho wrapper objects == operator, compares objects references if not within integer internal cache.

since 321 out of integer cache, == operator returns false, because references different (f1 refers different memory address f2).

when explicitly set references equal (with f2.set(f1.get())), it's not surprising program outputs true.

if set a between -128 , 127, program output true.


Comments

Popular posts from this blog

c# - Binding a comma separated list to a List<int> in asp.net web api -

Delphi 7 and decode UTF-8 base64 -

html - Is there any way to exclude a single element from the style? (Bootstrap) -