在java中存在equals进行对数据比较是否相同,但在正常情况下还存在“==”也可以表示对数据的对比,在java当中,一般来说是可以这样解释的
在基础数据类型的比较的时候,应该使用“=="进行比较其值
当存在引用数据类型的时候,可以使用“==”用于对其在内存中存放地址进行比较
但在第二种情况下,除非是new出来一个新的对象,他们的比较结果会是true否则比较之后的结果会是false,因为在new了之后会重新开辟一块新的堆内存空间。
(开始没有仔细看,在后面的学习中重新开辟空间和规则集中的hashset什么的出现了冲突,因为在规则集当中很多情况下并不允许出现相同内存信息的东西,所以一般会将所有放入相同的元素放在第一次出现的那个元素的地址,即认为后面出现的都是它,扯远了)
在equals方法中,这个方法默认的行为是对比两个对象的内存地址,但这个在一些特殊的Object超类的子类(String,Inter,Date)中重写(因为只是单纯比较地址意义并不大)在没有复写的情况下equals和==中对于地址的比较是相同的。但复写之后的情况需要单独拿出来
String类中被重写的情况
在idea中打开String可以找到关于equals复写的代码
/**
* 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.
*
* <p>For finer-grained String comparison, refer to
* {@link java.text.Collator}.
*
* @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 aString = (String)anObject;
if (coder() == aString.coder()) {
return isLatin1() ? StringLatin1.equals(value, aString.value)
: StringUTF16.equals(value, aString.value);
}
}
return false;
}
值得注意的是在下面的这一句 ,在这里通过对两句字符串进行了一次比较。并且希望得到true的返回值
但在(coder()=aString.coder())这一行存在一定的问题,希望有大佬可以帮忙解释一下
this == anObject
在下面会出现几种特殊的情况
package qi;
public class StringDemo {
public static void main(String[] args){
String s1="hello";
String s2 = "hello";
System.out.println(s1==s2);
}
}
还有一份程序是这个样子的
package qi;
public class StringDemo {
public static void main(String[] args){
String s1="hello";
String s2=new String("hello");
String s3 = s2;
System.out.println(s1==s2);
System.out.println(s1==s3);
System.out.println(s2 == s3);
System.out.println(s3.equals(s2));
System.out.println(s1.equals(s3));
System.out.println(s2.equals(s3));
}
}
可以得到结果是
false
false
true
true
true
true