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);
  }
}

为什么在and'a'中使用时结果为假?为什么未注释时结果为真?请解释我在哪里犯了错误。f1f2f2.Set(f1.Get());

4

2 回答 2

5

在该.isEquals()方法中,您将包装对象与==运算符进行比较,如果对象引用不在Integer内部缓存中,则该运算符将比较这些对象引用。

由于321超出Integer缓存,==运算符返回false,因为引用不同(f1指的内存地址与 不同f2)。

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

如果您设置a-128and之间127,程序将输出true.

于 2015-08-31T09:35:47.817 回答
3

a自动装箱Integerand forint a = 321;你会有两个不同Objects的 for f1and f2

例如

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

并且因为比较参考而不是值,所以a1 == a2您应该使用方法来检查方法中的值。false==equalsisEqual

于 2015-08-31T09:35:55.320 回答