String的isEmpty()方法的坑

最近踩了一个String的isEmpty()这个方法的坑,就是当string的值为null的时候,s.isEmpty()会抛出一个空指针异常。所以去看了一下它的isEmpty()这个方法

 public boolean isEmpty() {
    return count == 0;
    }

  /** The count is the number of characters in the String. */
    private final int count;

当count的值为0的时候返回true,反之false,前提是string已经创建了对象分配了内存,但是当string的值为null的时候是不会创建的,所以用这个方法区判断就会出现空指针异常了。

isEmpty()可以用来判断“”和new String()但不能用来判断null.

posted @ 2020-05-18 09:41  魔力员  阅读(3238)  评论(0)    收藏  举报

欢迎各位大佬交流指导 qq:704351018