1. "null" 字符串判断
1.1 String常量比较
@Test
public void demo() {
String a = "null";
String b = "null";
if (a == "null") {
System.out.println("a==null");
}
if (a == b) {
System.out.println("a==b");
}
}
1.2 String 对象比较
@Test
public void demo() {
String content = "null,null,null";
String str = content.split(",")[0];
if (str != "null") {
System.out.println("str!=null");
}
}
输出结果:str!=null
2. 问题分析
![](https://img.haomeiwen.com/i20154612/1ba5c21bedf4bf70.png)
示例一:
System.out.println(a == str); // false
示例二:
System.out.println(str != "null"); // true
System.out.println(str == "null"); // false
示例三:
System.out.println(str == str2); // false
2.2 源码分析
// java.lang.String
public String[] split(String regex) {
return split(regex, 0);
}
public String[] split(String regex, int limit) {
// ...
if (!limited || list.size() < limit)
list.add(substring(off, value.length));
// ...
}
public String substring(int beginIndex, int endIndex) {
// ...
return ((beginIndex == 0) && (endIndex == value.length)) ? this
: new String(value, beginIndex, subLen);
}
3. 解决方案
== 改为 equals
网友评论