以下程序段的输出结果为:
public class EqualsMethod { public static void main(String[] args) { Integer n1 = new Integer(47); Integer n2 = new Integer(47); System.out.print(n1 == n2); System.out.print(","); System.out.println(n1 != n2); } }
public class EqualsMethod { public static void main(String[] args) { Integer n1 = new Integer(47); Integer n2 = new Integer(47); System.out.print(n1 == n2); System.out.print(","); System.out.println(n1 != n2); } }
false,false
false,true
true,false
true,true
1. -128<= x<=127的整数,将会直接缓存在IntegerCache中,那么当赋值在这个区间的时候,不会创建新的Integer对象,而是从缓存中获取已经创建好的Integer对象;当大于这个范围的时候,直接new Integer来创建Integer对象。
Integer n1 = 47; Integer n2 = 47; System.out.print(n1 == n2); System.out.print(","); System.out.println(n1 != n2); //output:true,false Integer n3 = Integer.valueOf(47); Integer n4 = Integer.valueOf(47); System.out.print(n3 == n4); System.out.print(","); System.out.println(n3 != n4); //output:true,false
public static void main(String[] args) { //Integer 通过new创建 Integer n1=new Integer(127); Integer n2=new Integer(127); System.out.println("通过new方式创建值为:"+(n1==n2)); //直接赋值在-128~127之间 Integer n3=127; Integer n4=127; System.out.println("直接赋值在-128到127之间:"+(n3==n4)); //使用ValueOf与直接赋值的对比(未超出) Integer n5=Integer.valueOf(127); System.out.println("使用ValueOf与直接赋值的对比"+(n4==n5)); //超出-128~127的值比较 Integer n6=128; Integer n7=128; System.out.println("赋值超出128为:"+(n6==n7)); //使用ValueOf与直接赋值的对比(超出) int n8=Integer.valueOf(128); System.out.println("使用ValueOf与直接赋值的对比"+(n8==n7)); }
”==“可以用于原始值进行比较,也可以用于对象进行比较,当用于对象与对象之间比较时,比较的不是对象代表的值,而是检查两个对象是否是同一对象,这个比较过程中没有自动装箱发生。进行对象值比较不应该使用”==“,而应该使用对象对应的 equals 方法。
equals方法在Integer和String这些类中被重写,变成先比较类型,再比较值,而不是比较地址。在用户自定义的类中,没有重写equals方法时,使用的是Object类的equals方法,里面比较的是对象的地址。
==可用于基本类型和引用类型:当用于基本类型时候,是比较值是否相同;当用于引用类型的时候,是比较对象是否相同。
"=="和"!="比较的是地址 指第一个new()c出来的地址
所以因为两次new() 分出的内存也不同
所以
System.out.print(n1 == n2);返回 false
!=就返回true
所以
答案:B