Java代码中的奇怪逻辑错误

Abu*_*que 3 java lambda method-reference

interface New<T> {
   boolean func(T n, T v);
}
Run Code Online (Sandbox Code Playgroud)
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;
}
Run Code Online (Sandbox Code Playgroud)
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);
  }
}
Run Code Online (Sandbox Code Playgroud)

为什么当结果为假'a'两种使用f1f2?为什么在f2.Set(f1.Get());取消注释时结果是正确的?请解释我在哪里弄错了.

Kon*_*kov 5

在该.isEquals()方法中,您将比较包装器对象与==操作符,如果这些对象引用不在Integer内部高速缓存中,则会对其进行比较.

由于321超出了Integer缓存,==操作符返回false,因为引用不同(f1指的是不同的内存地址f2).

当您明确地将引用设置为相等(with f2.Set(f1.Get()))时,程序输出就不足为奇了true.

如果你设置a-128和之间的东西127,程序将输出true.