一、“==”
在Java中,对于基本类型,“==”比较的是值。上代码:
int in1=10;
int in2=10;
System.out.println("in1==in2"+(in1==in2));//in1==in2true
而对于引用类型,比较的是地址:
String str1=new String("123");
String str2=new String("123");
String str3="123";
String str4="123";
System.out.println("str1==str1"+" "+(str1==str2)); //false
System.out.println("str1==str3"+" "+(str1==str3)); //false
System.out.println("str3==str4"+" "+(str3==str4)); //true
注意地址的变化。通过new的是实例对象,保存在内存的堆内,直接定义的值保存在常量池内。所以地址不对。
此时需要注意一个点,对于包装类型(Integer):直接举例说明吧,上代码:
Integer in1=100;
Integer in2=100;
Integer in3=130;
Integer in4=130;
System.out.println(in1==in2);//true
System.out.println(in3==in4);//false
具体的原因请查看:JAVA-数据类型。(当然是为了大家可以更好的更正我的错误咯!)
二、equals()方法;
注意:这是一个方法,那么要了解一个方法的原理,最直接的方法就是查看源码后实践。
话不多说,直接上源码:
public boolean equals(Object obj) {
if (obj instanceof Integer) {
return value == ((Integer)obj).intValue();
}
return false;
}
查看源码以后,发现equals()比较的是值的属性(对于基本的,也就是比较的是值)。但是,既然是方法,那么就可以对方法进行重写或者覆盖。上代码:
Integer in1=100;
Integer in2=100;
Integer in3=130;
Integer in4=130;
// System.out.println(in1==in2);//true
// System.out.println(in3==in4);//false
System.out.println(in1.equals(in2)); //true
System.out.println(in3.equals(in4)); //true
再来看一个equals()被重写过的:
String str1=new String("520");
String str2=new String("520");
System.out.println(str1==str2); //false
System.out.println(str1.equals(str2)); //true
,这里需要进入源码查看:
/**
* Compares this string to the specified object. The result is {@code
* true} if and only if the argument is not {@code null} and is a {@code
* String} object that represents the same sequence of characters as this
* object.
*
* @param anObject
* The object to compare this {@code String} against
*
* @return {@code true} if the given object represents a {@code String}
* equivalent to this string, {@code false} otherwise
*
* @see #compareTo(String)
* @see #equalsIgnoreCase(String)
*/
public boolean equals(Object anObject) {
if (this == anObject) {
return true;
}
if (anObject instanceof String) {
String anotherString = (String)anObject;
int n = value.length;
if (n == anotherString.value.length) {
char v1[] = value;
char v2[] = anotherString.value;
int i = 0;
while (n-- != 0) {
if (v1[i] != v2[i])
return false;
i++;
}
return true;
}
}
return false;
}
发现,最终比较的还是值。
equals()不能用于基本类型的比较。上图片;
并没有equals()方法.
总结;在正常的情况下(没有重写),"=="和equals的效果相同,对于重写了equals方法的,equals方法比较的对象的内容。(注意Integer类)