equals 与 ==
作者:互联网
写代码时,equals 和 == 都是常用的手段检测两者是否相等,那么具体有什么异同呢?我们来结合源码分析一下。
==
== 是操作符,对于基本类型变量(如 int 、 short 、 long 等),它们没有 equals 方法,因此一般都是用 == 进行比较。
比较的是它们的值。
equals
对于引用型变量,它们都是继承自 Object 类,对于同类型的比较,如果没有复写 equals 方法的话,默认是比较它们在内存中的值。
源代码如下:
public boolean equals(Object obj) { return (this == obj); }
对于复写过 equals 方法的类,它们的对象调用该方法,呈现的效果就不太一样了。
例如String,该类的实现代码如下:
/**
* 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 ,否则比对值的情况。
有兴趣的朋友请查阅下Java源码,从更深的角度理解这个问题。
源码赛高~
标签:code,return,String,object,equals,anObject 来源: https://www.cnblogs.com/mengtaozhang/p/13437470.html