Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if List<obj> is null?

Tags:

java

list

I have a list that takes a list from my server. this list will hold whatever the server finds at the database ex.

List<OBJ> lstObj = new Arraylist<OBJ>;

Service.getOBJ(new AsyncCallback<List<OBJ>>(){
    @Override
    public void onFailure(Throwable caught) {
        caught.printStackTrace();
    }

    @Override
    public void onSuccess(List<OBJ> result) {
        //line to check if result is null
    }
});

I have tried

if(result==null){
}

and also tried

if(result.isempty(){
}

but it didnt work. the list will be null if the server doesnt find any record from the database. all i need to do is check if the list is empty.

like image 845
corgrin Avatar asked Nov 28 '22 05:11

corgrin


2 Answers

Checking if the list is empty and checking if result is null are very different things.

if (result == null)

will see if the value of result is a null reference, i.e. it doesn't refer to any list.

if (result.isEmpty())

will see if the value of result is a reference to an empty list... the list exists, it just doesn't have any elements.

And of course, in cases where you don't know if result could be null or empty, just use:

if (result == null || result.isEmpty())
like image 191
Jon Skeet Avatar answered Dec 11 '22 06:12

Jon Skeet


Check number of elements in resulting List:

if (0==result.size()) {

    // Your code
}
like image 35
Rodion Altshuler Avatar answered Dec 11 '22 06:12

Rodion Altshuler