开发者

How to know if specified object in ArrayList is null?

开发者 https://www.devze.com 2023-03-17 06:23 出处:网络
I want to know if an Object in an ArrayList is null. If it\'s null, then it shouldn\'t do anything. Example:

I want to know if an Object in an ArrayList is null. If it's null, then it shouldn't do anything. Example:

if(!(theList.get(theIndexofObject) == null)){
   do something...
}
else{
   do nothing...
}

This doesn't work, because it throws an exception cause of the '.get()'-method. Any id开发者_如何学运维eas to solve this problem?


Use the contains() Method of your list:

boolean contains(Object o)


You are probably confused about how to use the API. Here is a simple example of how it works:

import java.util.ArrayList;
import java.util.List;

public class NullItems {
    public static void main(String[] args) {

        List<Object> items = new ArrayList<Object>();
        items.add("foo");
        items.add(null);
        items.add(25);

        for (int i = 0; i < items.size(); i++) {
            Object item = items.get(i);
            if (item != null) {
                System.out.println(item);
            }
        }

        // or shorter:
        for (Object item : items) {
            if (item != null) {
                System.out.println(item);
            }
        }
    }
}


You are using the get method wrong. You need to pass the index an item is at to the get method. You could use the contains method to see if the object is in the ArrayList.

Example:

if(theList.contains(theObject))
   //do something

Otherwise you could use a try and catch which seems confusing and hard to read so I would strongly not recommend doing the following but have included it to show you:

for(int i=0; i<theList.size(); i++)
{
    try
    {
       if(!(theList.get(i) == null))
       {
           //do something
       }
       else
       {
           //do nothing
       }
    }
    catch(NullPointerException npe)
    {
        //do something else
    }
}

Alternatively use a for-each loop.


In javaScript itemArray.length, for java u have to use ARRAY.size() insted of length function

 var itemArray=//Assign some list of value;
    for (var i = 0; i < itemArray.length; i++){

          if(itemArray[i].value == null){
             Do nothing
              }else{
                 Do something
              }
    }


i think that your arraylist is null chang first condition to:

if(theList!=null && !(theList.get(theIndexofObject) == null)){
    // do something...
}
else{
    // do nothing...
}


The method arrayList.size() returns the number of items in the list - so if the index is greater than or equal to the size(), it doesn't exist.


if(!(theList.get(theIndexofObject) == null)){
   do something...
}
else{
   do nothing...
}

instead of writing this code.Try in the below format,I think you will get answer

if(theList.get(theIndexofObject)!= null)){
   do something...
}
else{
   do nothing...
}
0

精彩评论

暂无评论...
验证码 换一张
取 消