Java Integer int ==比較の問題

私はベテランだと思いますが、気をつけないと穴に落ちてしまいます。

package xcg.util;

public class Test {

	public static void main(String[] args) {
		Integer a=1;
		Integer b=1;
		Integer c=new Integer(1);
		Long d=new Long(1L);
		
		System.out.println("Integer a=1,Integer b=1,a==b?"+(a==b));
		System.out.println("Integer a=1,Integer b=1,a.equals(b)?"+(a.equals(b)));
		System.out.println("Integer a=1,Integer c=new Integer(1),a==c?"+(a==c));
		System.out.println("Integer a=1,Integer c=new Integer(1),a==c?"+(a.equals(c)));
		System.out.println("Integer a=1,Long d=1,a==d?语法错误");
		System.out.println("Integer a=1,Long d=1,a.equals(d)?"+(a.equals(d)));
		System.out.println("我的理解:==对象比较对象,简单类型比较值,对象比较简单类型则比较值,equals是同数据类型内容比较(不同数据类型即使值同但fase,例如同内容的String和StringBuffer比较结果为false),我的最终做法是:==配合.IntegerValue()或LongValue");
		System.out.println("Integer a=1,Long d=1,a.intValue()==d?"+(a.intValue()==d));
	}
}

操作の結果は次のとおりです。

整数a = 1、整数b = 1、a == b?true
整数a = 1、整数b = 1、a.equals(b)?true
整数a = 1、整数c =新しい整数(1)、a = = c?false
Integer a = 1、Integer c = new Integer(1)、a == c?true
Integer a = 1、Long d = 1、a == d?構文エラー
Integer a = 1、Long d = 1 、a.equals(d)?false
私の理解:==オブジェクトはオブジェクトを比較し、単純型は値を比較し、オブジェクトは単純型を比較し、値を比較し、equalsは同じデータ型のコンテンツを比較します(値が同じでもfaseであっても異なるデータ型)、私の最後のアプローチは次のとおりです。==協力します。IntegerValue()またはLongValue
Integer a = 1、Long d = 1、a.intValue()== d?true

 

おすすめ

転載: blog.csdn.net/xcg8818/article/details/105406280