我现在正在学习 arraylist,我不知道为什么有人像这样删除最后一个元素:
l = list.size();
.
if (list != null && !list.isEmpty()) {
list.remove(l);}
这不同于:
if (list != null ) {
list.remove(l);}
或
if (!list.isEmpty()) {
list.remove(l);}
?有人可以解释一下吗?
最佳答案
当您编写 list != null
时,您正在检查变量 list
是否为 null。以下面的代码为例:
ArrayList al = new ArrayList();
变量 al
不会是 null
因为我们已经将它分配给了一个 new ArrayList()
,但是它将是空的因为它不包含任何元素。
ArrayList al;
在上面的例子中,al
将是 null
,因为它还没有被初始化。
关于java - 为什么要在从列表中删除元素之前检查这两个条件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42371372/