Java中测试对象的等价性

Java中用于测试对象的等价性有三个操作符:== , != 和 Equals()

对于基本类型即int,boolean, byte 等等来说,==和 != 比较的是 基本类型的内容,这和c、c++是一样的;

public class Ex5 {	
	public static void main(String[] args) {		
		int i = 34;
		int ii = 34;
		System.out.println(i==ii);	
	}
}

//output: true

对于其他类型来说, == 和 != 比较的是对象的引用,显然是不等的,如果要比较对象之间的内容,对象所属的类型必须实现Equals()方法(大多数Java类库中都实现了Equals方法),如果没有实现Equals方法,会自动调用object中的Equals方法,而该方法是用来比较“地址”的,因此结果会是false。

public class Ex5 {	
	public static void main(String[] args) {
		
		Integer i1 = new Integer(34);
		Integer i2 = new Integer(34);
		System.out.println(i1==i2);	
		
		System.out.println(i1.equals(i2));
	}
}
//output:
//false
//true 

后来发现一个奇怪的问题,比如如下这段代码,输出的却是true。

public class Ex5 {	
	public static void main(String[] args) {		
		Integer i1 = 34;
		Integer i2 = 34;
		System.out.println(i1==i2);		
	}
}
//output:
//true

Integer i = 34这种赋值方式会调用Integer的ValueOf()缓存(如果不在-128~127之间则不会缓存)为基本类型(jvm会为Integer预先分配一部分内存,在以后有请求Integer对象时,若值位于-128~127时,系统都会让它指向这个预分配好的Integer对象)

public class Ex5 {	
	public static void main(String[] args) {		
		Integer i1 = 34;
		Integer i2 = 34;
                Integer i3 = Integer.ValueOf(34);
		System.out.println(i1==i2);
                System.out.println(i1==i3);
        }     
} 
//output: 
//true
//true
    

Integer与int比较相等时,会将Integer转换为进行转换为int再比较,所以最终比较的是内容。  

 

posted on 2015-08-27 20:54  aituming  阅读(385)  评论(0编辑  收藏  举报