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!"); } }
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.
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.
No. An ArrayList can be empty (or with nulls as items) an not be null.
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 ).
As simply as:
if (numbers.isEmpty()) {...}
Note that a quick look at the documentation would have given you that information.
You should use method listName.isEmpty()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With