[java] Java ArrayList - Check if list is empty

How can I check if a list is empty? If so, the system has to give a message saying List is empty. If not, the system has to give a message saying List is not empty. Users can enter numbers, -1 to stop the program. This is the code I now have, but this doesn't work, it always says 'List isn't empty'.

import java.util.*;
import javax.swing.JOptionPane;

public class ArrayListEmpty 
{
    public static void main(String[] args) 
    {
        List<Integer> numbers = new ArrayList<Integer>();
        int number;
        do {
            number = Integer.parseInt(JOptionPane.showInputDialog("Enter a number (-1 to stop)"));
            numbers.add(number);
        } while (number != -1);
        giveList(numbers);
    }

    public static void giveList(List<Integer> numbers)
    {
        if (numbers != null)
            JOptionPane.showMessageDialog(null, "List isn't empty");
        else
            JOptionPane.showMessageDialog(null, "List is empty!");
    }
}

This question is related to java arraylist

The answer is


Source: CodeSpeedy Click to know more Check if an ArrayList is empty or not

import java.util.ArrayList;
public class arraycheck {
public static void main(String args[]){
ArrayList<Integer> list=new ArrayList<Integer>();

    if(list.size()==0){
        System.out.println("Its Empty");

    }
    else
        System.out.println("Not Empty");

   }

}

Output:

run:
Its Empty
BUILD SUCCESSFUL (total time: 0 seconds)

Good practice nowadays is to use CollectionUtils from either Apache Commons or Spring Framework.

CollectionUtils.isEmpty(list))

Alternatively, you may also want to check by the .size() method. The list that isn't empty will have a size more than zero

if (numbers.size()>0){
//execute your code
}

You should use method listName.isEmpty()


Your original problem was that you were checking if the list was null, which it would never be because you instantiated it with List<Integer> numbers = new ArrayList<Integer>();. However, you have updated your code to use the List.isEmpty() method to properly check if the list is empty.

The problem now is that you are never actually sending an empty list to giveList(). In your do-while loop, you add any input number to the list, even if it is -1. To prevent -1 being added, change the do-while loop to only add numbers if they are not -1. Then, the list will be empty if the user's first input number is -1.

do {
    number = Integer.parseInt(JOptionPane.showInputDialog("Enter a number (-1 to stop)"));
    /* Change this line */
    if (number != -1) numbers.add(number);
} while (number != -1);