What is the method in Java to check if a collection is empty?

There are several ways to check if a collection is empty in Java.

  1. By using the isEmpty() method of a collection: this method returns a boolean value indicating whether the collection is empty or not. For example:
List<String> list = new ArrayList<>();
if(list.isEmpty()) {
   System.out.println("集合为空");
}
  1. You can use the size() method of a collection to determine the number of elements in the collection. By checking if the size is 0, you can determine if the collection is empty. For example:
Set<Integer> set = new HashSet<>();
if(set.size() == 0) {
    System.out.println("集合为空");
}
  1. Use the conditions of the set: directly check if the set is null or if it contains elements. For example:
Map<String, Integer> map = new HashMap<>();
if(map == null || map.isEmpty()) {
    System.out.println("集合为空");
}

These methods can all be used to determine if a set is empty, and the appropriate method depends on the specific scenario and requirements.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds