Java ArrayList - Check if list is empty

前端 未结 6 873
小蘑菇
小蘑菇 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:03

    As simply as:

    if (numbers.isEmpty()) {...}
    

    Note that a quick look at the documentation would have given you that information.

    0 讨论(0)
  • 2020-12-05 13:09

    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)
    
    0 讨论(0)
  • 2020-12-05 13:17

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

    CollectionUtils.isEmpty(list))
    
    0 讨论(0)
  • 2020-12-05 13:17

    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
    }
    
    0 讨论(0)
  • 2020-12-05 13:20

    You should use method listName.isEmpty()

    0 讨论(0)
  • 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<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);
    
    0 讨论(0)
提交回复
热议问题