打开org.apache.commons.lang包下面的StringUtils.class源码
查看源码
/**
* <p>Compares two Strings, returning <code>true</code> if they are equal.</p>
*
* <p><code>null</code>s are handled without exceptions. Two <code>null</code>
* references are considered to be equal. The comparison is case sensitive.</p>
*
* <pre>
* StringUtils.equals(null, null) = true
* StringUtils.equals(null, "abc") = false
* StringUtils.equals("abc", null) = false
* StringUtils.equals("abc", "abc") = true
* StringUtils.equals("abc", "ABC") = false
* </pre>
*
* @see java.lang.String#equals(Object)
* @param str1 the first String, may be null
* @param str2 the second String, may be null
* @return <code>true</code> if the Strings are equal, case sensitive, or
* both <code>null</code>
*/
public static boolean equals(String str1, String str2) {
return str1 == null ? str2 == null : str1.equals(str2);
}
翻译一下注释
/ * *
public static boolean equals(String str1, String str2) {
return str1 == null ? str2 == null : str1.equals(str2);
}
这里传入两个String类型的参数,最后return一个boolean类型。
return用了一个三元运算符
大致就是这样格式 a?b:c
a代表条件,如果为true,只运行b,,如果为false,只运行c
上面源码就是先判断str1是否等于null
如果为空,
接着判断str2是否为空,如果也为空返回true,因为两个都等于null,所以两个也相等,如果str2不等于null,返回false,然而str1已经等于null,所以两个必定不相等
如果不为空
接着判断str1.equals(str2) 这是调用了String.class的equals的方法
看看源码,因为StringUtils.equals里面已经判断null了,所以这个里面也就不判断是否为null了
/**
* 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)
*/
/ * *
将该字符串与指定的对象进行比较。结果是{ @code
如果且仅当参数不是@code null且是@code时
字符串对象表示与此相同的字符序列
*对象。
*
* @param anObject
用来比较这个@code字符串的对象
*
@return@code,如果给定对象表示一个@code字符串
等价于这个字符串,@code是假的
*
* @see # compareTo(字符串)
* @see # equalsIgnoreCase(字符串)
* /
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;
}
如果是对象,直接用==判断两个对象是否同一个对象,
if (this == anObject) {
return true;
}
不是的话判断长度是否相等value.length,
if (n == anotherString.value.length)
如果长度相等判断每个字符是否相等
if (v1[i] != v2[i])
总结,StringUtils里面的equals方法主要是判断了一下两个对象是否等于null,等于null情况下的相等,两种情况,
后面调用了string.equals来判断是否相等,这里面也不再判断是否等于null了,这里面主要采用对象直接比较,是否属于同一个对象,
不属于的话,比较长度,
长度相等的话,长度内部还比较了数组每个位置的字符是否相等,