Home > Java > JavaBase > Java determines whether a collection object is empty

Java determines whether a collection object is empty

王林
Release: 2019-11-21 09:38:07
Original
3920 people have browsed it

Java determines whether a collection object is empty

The List.isEmpty() method in Java collection class is used to determine whether the collection object is empty. If it is empty, it returns true, otherwise it returns false.

Syntax:

isEmpty()
Copy after login

Application:

This example uses the implementation class ArrayList of the List interface to initialize a list object list, add 4 elements to the list, and then call The isEmpty method determines whether the list object is empty and outputs the determination result, then executes the clear method to remove all elements from the list, and finally executes the isEmpty method again to determine whether the list object is empty and outputs the determination result.

The code is as follows:

public static void main(String[] args){
    List<String>list = new ArrayList<String>();
    list.add("保护环境");  //向列表中添加数据
    list.add("从我做起");  //向列表中添加数据
    list.add("爱护地球");  //向列表中添加数据
    list.add("从我做起");  //向列表中添加数据
    boolean empty = list.isEmpty();
    if(empty){
    System.out.println("该列表为空");
  }else{
    System.out.println("该列表不为空");
  }
    list.clear();  //从列表中移除所有元素
    System.out.println("执行clear方法后");
    empty = list.isEmpty();
    if(empty){
    System.out.println("该列表为空");
  }else{
    System.out.println("该列表不为空");
  }
}
Copy after login

The running results are as follows:

该列表不为空
执行clear方法后
该列表为空
Copy after login

Recommended tutorial: java quick start

The above is the detailed content of Java determines whether a collection object is empty. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template