一、概述
在Java中,List是一个非常常见的数据结构。在进行List操作时,一个经常被用到的问题就是判断一个List是否为空,这时我们就会用到List的isEmpty方法。下面将从源码角度、使用场景以及实现原理等多个方面进行详细阐述。
二、源码角度
List的isEmpty方法源码如下:
/** * 返回list是否为空 * @return true-空,false-不为空 */ public boolean isEmpty() { return size == 0; }
可以看到,List的isEmpty方法的实现非常简单,它只是返回了List的size属性是否为0,即List是否为空。所以,从源码层面讲,List的isEmpty方法是一种非常高效的实现方式。
三、使用场景
在前面我们已经提到了,判断List是否为空是非常常见的问题。底层实现使用的是size属性来判断是否为空,其具有常数时间复杂度,因此非常适合高频使用的场景。在实际的代码开发中,我们在对List进行读取、修改等操作前,都应该先判断一下该List是否为空,以避免出现NullPointerException等问题。
四、实现原理
在大部分情况下,判断List是否为空所使用的方法即是size是否为0,但是,在有些实现中,isEmpty方法与ArrayList和LinkedList的不同实现有关。比如,LinkedList的实现是直接判断first是否为空,而不是判断size的大小。
从List的数据结构上来看,我们可以发现,判断一个List是否为空,最重要的还是要看它的元素个数。因此,在LinkedList中,将first的值是否为空与size是否为0联系在了一起,就可以更加高效地判断List是否为空了。
/** * Returns true if this deque is empty. * * @return {@code true} if this deque is empty, {@code false} otherwise */ public boolean isEmpty() { return size == 0; } /** * Links e as first element. */ private void linkFirst(E e) { //先保存头结点 final Node f = first; //新建一个节点连到头部 final Node newNode = new Node(null, e, f); //重新将头结点赋值为新节点 first = newNode; //如果原来的头结点为空,则说明这个链表是空的 if (f == null) last = newNode; else f.prev = newNode; size++; modCount++; }
而在ArrayList的实现中就不需要像LinkedList那样进行特殊处理,因为ArrayList的size属性就是它元素的个数。
/** * Returns true if this list contains no elements. * * @return true if this list contains no elements */ public boolean isEmpty() { return size == 0; } /** * Increases the capacity of this ArrayList instance, if necessary, * to ensure that it can hold at least the number of elements specified * by the minimum capacity argument. * * @param minCapacity the desired minimum capacity */ private void grow(int minCapacity) { // overflow-conscious code int oldCapacity = elementData.length; if (minCapacity > oldCapacity) { Object oldData = elementData; int newCapacity = (oldCapacity * 3)/2 + 1; if (newCapacity < minCapacity) newCapacity = minCapacity; // minCapacity is usually close to size, so this is a win: elementData = Arrays.copyOf(elementData, newCapacity); modCount++; } }
五、代码示例
下面给出一个示例,演示如何使用List的isEmpty方法检查List是否为空:
public class ListIsEmptyDemo { public static void main(String[] args) { List list = new ArrayList(); if (list.isEmpty()) { System.out.println("list为空"); } else { System.out.println("list不为空"); } list.add("apple"); if (list.isEmpty()) { System.out.println("list为空"); } else { System.out.println("list不为空"); } } }
输出结果为:
list为空 list不为空
六、总结
本文从源码角度、使用场景以及实现原理等多个方面详细阐述了List的isEmpty方法。可以看到,List的isEmpty方法的实现非常简单,它只是返回了List的size属性是否为0,即List是否为空。在实际开发中,我们也需要时刻关注List是否为空,尤其是在进行读取、修改等操作前,首先检查List是否为空,以避免出现空指针等异常。
原创文章,作者:小蓝,如若转载,请注明出处:https://www.506064.com/n/191918.html