1、“==” 用來比較兩個操作元是否相等,操作元可以是基本數據類型,也可以是引用類型。. 2、equals()方法用來比較兩個對象是否相等。
對象為基本類型 int a=1,b=2; a==b //false int a=1,b=1; a==b //true
對象為引用類型 Integer int1=new Integer(1); Integer int2=new Integer(1); Integer int3=int1; int1==int2 //false int1.equals(int2) //true int1==int3 //true 引用了同一個對象 int1.equals(int3) //true String str1=“hello”,str2=“world” str1==str2 //false str1.equals(str2) //true
總結:實際運用中,基本類型的比較一般采用“==”,String類型的比較一般采用equals(),比如if(a.equals(“hello”))
新聞熱點
疑難解答