一、概述
在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/zh-tw/n/191918.html