Java中equals和==的区别(详细概述)
详细结论
== 比较的是变量(栈)内存中存放的对象的(堆)内存地址,用来判断两个对象的地址是否相同,即是否是指相同一个对象。比较的是真正意义上的指针操作。基本数据类型中比较的是值是否相等。
equals用来比较的是两个对象的内容是否相等,由于所有的类都是继承自java.lang.Object类的,所以适用于所有对象,如果没有对该方法进行覆盖的话,调用的仍然是Object类中的方法,而Object中的equals方法返回的却是==的判断。
基本数据类型
byte,short,char,int,long,float,double,boolean
基本数据类型之间的比较需要用双等号(==),因为他们比较的是值是否相等
public static void main(String[] args) {
int a = 1;
int b = 2;
int c = 1;
System.out.println(a == b); //false
System.out.println(a == c); //true
System.out.println(a.equals(b)); //错误,编译不能通过
}
引用数据类型
a、== 进行比较
String,interface,abstract,String[](数组类型等)
类,接口,数组等非基本数据类型,String也是数据引用数据类型,也是一个class类。
== 进行比较的时候,比较的是他们在内存中的存放地址,所以,除非是同一个new出来的对象,他们的比较后的结果为true,否则比较后结果为false。因为每new一次就会重新开辟一个新的堆内存空间。
//定义普通类进行比较
public class Entry {
private String id;
public Entry() {
}
public Entry(String id) {
this.id = id;
}
}
public static void main(String[] args) {
Entry entry1 = new Entry();
Entry entry2 = new Entry();
Entry entry3 = entry1;
System.out.println(entry1 == entry2);//false,不同对象,不同地址
System.out.println(entry1.equals(entry3));//true 同一对象,同一地址
System.out.println(entry1.equals(entry2));//false 没有覆盖,和==方法比较一样
System.out.println(entry1 == entry3);//true 没有覆盖,和==方法比较一样
}
b、equals方法比较
所有的类都是继承与Object这个基类的,在Object类中定义了一个equals方法,这个方法的初始行为是比较对象的内存地址,但在一些类库中已经重写了这个方法(一般都是用来比较对象的成员变量值是否相同),比如:String,Integer,Date 等类中,所以他们不再是比较类在堆中的地址了。
Object类中源码
//Object中的equals方法,不进行覆盖,就意味着==进行比较
public boolean equals(Object obj) {
return (this == obj);
}
String中的源码
private final char value[];
//vlaue[]中的元素进行一一对比,也就是比较内容
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;
}
Integer中的源码
//值进行比较
public boolean equals(Object obj) {
if (obj instanceof Integer) {
return value == ((Integer)obj).intValue();
}
return false;
}
//这个方法的对象创建在[-128-127]直接,直接返回缓存
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
public static void main(String[] args) {
Integer a = 12; //反编译可知,其实调用的是valueOf()方法
Integer b = 12;
Integer c = 13;
Integer d = 232;
Integer e = 232;
Integer f = new Integer(12);
Integer g = new Integer(12);
System.out.println(a == b); //true 在缓存范围,[-128,127],不会创建新对象
System.out.println(a == c); //false 不是同一个对象,地址不一样
System.out.println(d == e); //false 不再缓存范围,[-128,127],都会直接创建新对象
System.out.println(f == g); //false new一定会创建新对象,不同的对象,地址不一样
System.out.println(f == a); //false new一定会创建新对象,不同的对象,地址不一样
System.out.println(f.intValue() == a); //true .inValue()取值基本数据类型,a对象会自动拆箱,进行基本数据类型比较
System.out.println(f.equals(a));// true 比较的是值
}
Integer a = 12的反编译代码,调用的是valueOf()方法
既然这么说Integer的包装类具有缓存,那么其他的是不是也有?可以在源码中得知:
Character 部分缓存 [0, 127] 固定范围,不可修改
Boolean 全部缓存 true/false 固定范围,不可修改
Byte 全部缓存 [-128, 127] 固定范围,不可修改
Short 部分缓存 [-128, 127] 固定范围,不可修改
Integer 部分缓存 [-128, 127] 下限固定,上限可修改,-XX:AutoBoxCacheMax=上限值,进行修改
Long 部分缓存 [-128, 127] 固定范围,不可修改
Float 无
Double 无
public static void main(String[] args) {
String s1 = "abc";
String s2 = "abc";
String s3 = new String("abc");
String s4 = new String("abc");
String s5 = s1;
String s6 = s3;
System.out.println(s1 == s2);//true 均指向字符串常量池对象
System.out.println(s1.equals(s2)); //true 只进行对比
System.out.println(s3 == s1); // false 具有不同的地址进行比较
System.out.println(s3 == s4); //false 两个引用指向堆中的不同对象
System.out.println(s3.equals(s1)); //true 值进行比较
System.out.println(s3.equals(s4)); //true 值进行比较
System.out.println(s1 == s5); //true 均指向字符串常量池对象
System.out.println(s6 == s3); //true 指向相同的对象
String s7 = "abcd";
String s8 = new String("abcd");
s8 = s8.intern();
System.out.println(s7 == s8);//true
//检查字符串池里是否存在"abc"这么一个字符串,如果存在,就返回池里的字符串;如果不存在,
//该方法会 把"abc"添加到字符串池中,然后再返回它的引用。
String ss1 = "abc";
final String ss2 = "a";
final String ss3 = "bc";
String ss4 = ss2 + ss3;
System.out.println(ss1 == ss4);//true 编译器所做的优化,但是不同版本的JVM结果会不同
StringBuffer sb1 = new StringBuffer("a");
StringBuffer sb2 = new StringBuffer("a");
System.out.println(sb1.equals(sb2)); //没有重新equals方法,==比较的是两个对象的地址
String sb3 = "java1";
String sb4 = new StringBuilder().append("ja").append("va1").toString();
System.out.println(sb4 == sb3.intern());
//true 看intern比较,直接从字符串常量池中获取如果有即直接返回
}
String中的intern方法
/**
* Returns a canonical representation for the string object.
* <p>
* A pool of strings, initially empty, is maintained privately by the
* class {@code String}.
* <p>
* When the intern method is invoked, if the pool already contains a
* string equal to this {@code String} object as determined by
* the {@link #equals(Object)} method, then the string from the pool is
* returned. Otherwise, this {@code String} object is added to the
* pool and a reference to this {@code String} object is returned.
* <p>
* It follows that for any two strings {@code s} and {@code t},
* {@code s.intern() == t.intern()} is {@code true}
* if and only if {@code s.equals(t)} is {@code true}.
* <p>
* All literal strings and string-valued constant expressions are
* interned. String literals are defined in section 3.10.5 of the
* <cite>The Java™ Language Specification</cite>.
*
* @return a string that has the same contents as this string, but is
* guaranteed to be from a pool of unique strings.
*/
public native String intern();
可以从上面的注释中得到:
翻译:String类的intern()方法:一个初始为空的字符串池,它由类String独自维护。当调用 intern方法时,如果池已经包含一个等于此String对象的字符串(用equals(oject)方法确定),则返回池中的字符串。否则,将此String对象添加到池中,并返回此String对象的引用。 对于任意两个字符串s和t,当且仅当s.equals(t)为true时,s.intern() == t.intern()才为true。所有字面值字符串和字符串赋值常量表达式都使用 intern方法进行操作。
总结:引用数据类型之间进行equals比较,在没有覆写equals方法的情况下,他们之间的比较还是内存中的存放位置的地址值,跟双等号(==)的结果相同;如果被复写,按照复写的要求来。
== 的作用:
基本类型:比较的就是值是否相同;
引用类型:比较的就是地址值是否相同;
equals 的作用:
引用类型:默认情况下,比较的是地址值,重写该方法后比较对象的成员变量值是否相同。