Java ArrayList - Check if list is empty

前端 未结 6 872
小蘑菇
小蘑菇 2020-12-05 13:00

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 Li

6条回答
  •  独厮守ぢ
    2020-12-05 13:28

    Your original problem was that you were checking if the list was null, which it would never be because you instantiated it with List numbers = new ArrayList();. 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);
    

提交回复
热议问题