Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java ArrayList - Check if list is empty

Tags:

java

arraylist

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!");     } } 
like image 391
STheFox Avatar asked Jan 03 '13 18:01

STheFox


People also ask

How do you check if an ArrayList is empty on an index?

try { s. get(i); } catch (IndexOutOfBoundsException e) { s. add(i, new Object());//Add something to fill this position. } If the Arraylist in the i position is null (empty), the code catch the exception and you can add something to fill that position.

Is list null or empty Java?

A simple solution to check if a list is empty in Java is using the List's isEmpty() method. It returns true if the list contains no elements. To avoid NullPointerException , precede the isEmpty method call with a null check.

Is an empty ArrayList null?

No. An ArrayList can be empty (or with nulls as items) an not be null.

Can we check if list is null Java?

You should do if(test!= null) instead (checking for null first). The method isEmpty() returns true, if an ArrayList object contains no elements; false otherwise (for that the List must first be instantiated that is in your case is null ).


2 Answers

As simply as:

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

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

like image 157
assylias Avatar answered Oct 05 '22 18:10

assylias


You should use method listName.isEmpty()

like image 33
Marcin Szymczak Avatar answered Oct 05 '22 16:10

Marcin Szymczak