最近在学习的时候遇到了这个问题:假设有一java 字符串:String str;
那么 str == null 和 str.isEmpty() 有什么实质上的区别:
划重点:String 类 是引用类(reference type),有别于java 8个primitive type( int, long, etc)
null: 该对象是否存在
isEmpty(): 该对象存在,值是否为空
String str == null: str的reference为空
String str == "": str的reference有值,为一个空字符串(empty string)
| str | str == null? | str.isEmpty()? |
| null | True | NullPointerException |
| "" | False | True |
| "Sometext" | False | False |
所以经常在写算法题的时候
public class solution{
public int someFunctionName(char[][] grid) {
//这边会使用两个判断来确认grid是否存在
if (grid == null || grid.length == 0 ){ return 0; }
}
}
参考: https://stackoverflow.com/questions/13689033/any-difference-between-string-null-and-string-isempty
571

被折叠的 条评论
为什么被折叠?



