一、isEmpty()方法判斷
Java中的List是一個集合類型,使用List可以存儲一組有序的元素;但是在處理集合時,經常會遇到需要判斷List是否為空的情況。可以通過List的isEmpty()方法來判斷List是否為空:
List<String> list = new ArrayList<>(); if (list.isEmpty()) { System.out.println("List為空!"); } else { System.out.println("List不為空!"); }
上述代碼使用isEmpty()方法來判斷List是否為空。如果List為空,則列印出「List為空!」;否則列印出「List不為空!」。
二、判斷List元素個數
另一種判斷List是否為空的方法,是通過判斷List中元素的數量是否為0來判斷。
List<Integer> list = new ArrayList<>(); if (list.size() == 0) { System.out.println("List為空!"); } else { System.out.println("List不為空!"); }
上述代碼中使用了List的size()方法來獲取List中元素的數量。如果List中元素的數量為0,則表示List為空,列印出「List為空!」;否則列印出「List不為空!」。
三、Objects.isNull()方法判斷
Java 8引入了Objects類來判斷對象是否為空。可以使用Objects類中的isNull()方法來判斷List是否為空。
List<Double> list = null; if (Objects.isNull(list)) { System.out.println("List為空!"); } else { System.out.println("List不為空!"); }
上述代碼中使用了Objects類中的isNull()方法來判斷List是否為空。如果List為空,則列印出「List為空!」;否則列印出「List不為空!」。
四、Collections類判斷List是否為空
Collections類是Java中對集合操作的工具類,其中包括了許多靜態方法,可以方便地對集合進行操作。在Collections類中,也提供了判斷List是否為空的方法。
List<String> list = new ArrayList<>(); if (Collections.emptyList().equals(list)) { System.out.println("List為空!"); } else { System.out.println("List不為空!"); }
上述代碼中使用了Collections類中的emptyList()方法來創建一個空List。然後將創建的空List與需要判斷的List進行比較,如果相等,則表示List為空,列印出「List為空!」;否則列印出「List不為空!」。
五、總結
以上就是幾種判斷List是否為空的方法。根據需求可以選擇合適的方法進行判斷,其中isEmpty()方法是最常用的方法。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/296228.html