equals() 与 == 的区别
1. == 的用法:
1.1 比较对象是基本类型
使用 == 系统会自动进行类型强制转换,所以只需要两个变量的值相等即可。如果不能强制转换则直接报错。
1.2 比较对象是引用类型
当比较的两个变量是引用类型,他们必须要指向同一个实例才会返回true,也就是比较的是两个对象的内存地址。如果这两个变量没有继承关系,则会直接报错。
String a
= "hello";
String b
= "hello";
System
.out
.println(a
==b
);
String a
= new String("hello");
String b
=new String("hello");
System
.out
.println(a
==b
);
第一个print会返回True, 因为对于字符串来说,当使用直接量 “hello”,JVM会使用常量池来管理
第二个会返回 False,若使用 new String(),JVM会先在常量池管理直接量 hello,再调用String的构造器创建一个新的String对象,该对象保存在对内存中。 所以a,b是两个不同的String对象的实例。
常量池专门用于管理在编译时被确定,并保存在已编译的.class文件中的一些数据,它包括了关于类,方法,接口中的常量还包括字符串常量。
2. equals()的用法
2.1 概述
只有引用类型才有equals方法:equals方法是由Object类提供的。所以基本类型是没有equals方法的。当然java为所有的基本类型都提供了一个对应的引用类型,比如 int -> Integer。
查看源代码可知 :默认的equals()底层实现就是 ==, 它一般是由子类来重写的。Java中很多类(String类 Date类 File类)等都对equals方法进行了重写
2.2 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 (!COMPACT_STRINGS
|| this.coder
== aString
.coder
) {
return StringLatin1
.equals(value
, aString
.value
);
}
}
return false;
}
只要两个字符串的sequence一样就会返回true.
总之,equals()是可由自己重写的,一切都是自己做主,所以要了解某一个类的equals()的用法,就是看源码。