我想知道ArrayList中的Object是否爲null。如果它爲空,那麼它不應該做任何事情。例如:如何知道ArrayList中的指定對象是否爲空?
if(!(theList.get(theIndexofObject) == null)){
do something...
}
else{
do nothing...
}
這不起作用,因爲它會拋出'.get()'方法的異常原因。任何想法來解決這個問題?
我想知道ArrayList中的Object是否爲null。如果它爲空,那麼它不應該做任何事情。例如:如何知道ArrayList中的指定對象是否爲空?
if(!(theList.get(theIndexofObject) == null)){
do something...
}
else{
do nothing...
}
這不起作用,因爲它會拋出'.get()'方法的異常原因。任何想法來解決這個問題?
使用列表的contains()
方法:
boolean contains(Object o)
您使用的是get
方法是錯誤的。您需要將項目所在的索引傳遞給get
方法。您可以使用contains
方法來查看對象是否在ArrayList中。
例子:
if(theList.contains(theObject))
//do something
否則,你可以使用try和catch,這似乎令人困惑,難以閱讀,所以我強烈不建議做以下但已經有包括它告訴你:
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
}
}
或者使用for-each循環。
在JavaScript itemArray.length,爲Java u必須使用ARRAY.size()insted的長度函數的
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
}
}
我認爲你的ArrayList是空嫦娥一號條件:
if(theList!=null && !(theList.get(theIndexofObject) == null)){
// do something...
}
else{
// do nothing...
}
您可能對如何使用API感到困惑。這裏是它如何工作的一個簡單的例子:)
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);
}
}
}
}
的方法arrayList.size(返回列表中的項目數量 - 所以,如果該指數大於或等於大小(),它不不存在。
if(!(theList.get(theIndexofObject) == null)){
do something...
}
else{
do nothing...
}
,而不是在下面的格式寫這篇code.Try,我想你會得到答案
if(theList.get(theIndexofObject)!= null)){
do something...
}
else{
do nothing...
}
這與OP的問題無關遇到。 –
你以相反的順序做了同樣的事情。 – ambarox
什麼異常?如果它是NullPointerException,*列表*爲空,而不是對象。此外,'ArrayList#get()'要求一個int(對象索引),而不是一個對象。 – BoltClock
你確定你的ArrayList本身不是null嗎?根據你的說法,你的程序邏輯已經倒退了。 –
ArrayList有一個get方法需要一個對象? –