1

I know the isEmpty() method used to check if an arraylist is empty, but I am trying to check if an arraylist is not empty. I tried to look online but I didn't find any useful information on how to do this. My code is like "while ArrayList is not empty then run code).

2
  • 15
    while(!myList.isEmpty())? Commented Feb 11, 2015 at 0:52
  • this should work thanks Commented Feb 11, 2015 at 0:54

5 Answers 5

7

Invert the result of isEmpty().

public boolean notEmpty(ArrayList a) {
    return !a.isEmpty();
}

That will tell you when a list is not empty.

Sign up to request clarification or add additional context in comments.

2 Comments

why do a method call, when you can directly do !list.isEmpty() ?
I prefer to call it negate.
1

Alternatively, you can also check whether the array is null by the length/size of the arraylist.

while(arrayListName.size() > 0 ){
//execute code
}

Comments

1

If you initialize arrays as null you can just check if they are not null:

List<String> myArray = null;

myArray = myFunction.getArrayValues;

if (myArray != null) {
  processArray (myArray);
}

Comments

0

This is easier to read for me

while (arrayList.isEmpty() == false) {
  //do something cool
}

Comments

0

Can be useful

    if (!arrayList.isEmpty() ){
            //execute code
            System.out.println(arrayList.get(arrayList.size()-1));
         }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.