2012-07-30 87 views
1

我有问题。 我想检查指定索引的ararylist是否索引是空的。 用户可以输入商店像7个项目到我的数组列表(索引0到6)。 所以我想检查索引7是否为空,如果它是空的,我将循环回到我的RoomSelection()。arraylist isEmpty()疑惑和问题

使用roomInfo(4+ xx)的Im使用IsEmpty。

IsEmpty命令是否用于检查整个数组列表是否为空?

如果是检查整个数组列表,可以使用其他方法检查索引7是否为空?

for (int x = 0; x < (Integer) roomInfo.get(2); x++) {//start of number of room loop(to check how many rooms user input) 

    for (int i = 0; i < (Integer) roomInfo.get(4 + xx); i++) { //start of number of add-on loop(to check how many add-on user input) 


     System.out.println("addOns array contains what? : " + addOns); // for my own reference 
     System.out.println("Enter Add-On option"); 
     ao2 = input.nextInt(); 
     while (ao2 > 4) { 
      System.out.println("Please enter again! Choose only option 1 to 4"); 
      ao2 = input.nextInt(); 
     } 
     addOnOpt = addOn[ao2 - 1]; 
     addOns.add(addOnOpt); 
     addOnPrice = priceAdd[ao2 - 1]; 
     addOns.add(addOnPrice); 
     System.out.println("Enter quantity required for Add-On option " + (i + 1) + ": "); 
     quan = input.nextInt(); 
     addOns.add(quan); 
     xx += 3; 
     System.out.println(" not null yet"); 
     if ((roomInfo.isEmpty(4 + xx) == true) {//if condition to check whether is the arrayllist of position is not null 
      System.out.println("null!"); 
      xx = 0; 
      Selection(); 
     } 


    }// end of add-on loop 

}//end of number of room loop 

回答

0

如果ArrayList有7个或更少的项目,或者您在索引7中添加了null,则第8项(索引7)将为“空”你需要测试这两个条件:

if(roomInfo.size() < 8 || roomInfo.get(7) == null) { 
    // index 7 is "empty" 
} 
+0

如果我的索引7没有任何东西,我需要做如果(roomInfo.size()<4 + xx)这将做对吗? – 2012-07-30 10:44:32

3

isEmpty()如果列表中没有项目,则返回true。

要知道是否有第7项,请使用size()方法检查列表的大小(优于或等于7)。

1

isEmpty() 测试此列表是否没有元素。

“如果是检查整个数组列表,我可以使用其他方法检查索引7是否为空?

比方说,你有这样的:

ArrayList<abc> list=new ArrayList<abc>(); 

abc.size()返回列表中元素的个数。 如果你想在指数8,如果存在的元素来检查,最简单的方法是看是否大小返回至少9 所以:

int indexExists=8; 
if(abc.size()>indexExists) 
    //do whatever with abc.get(indexExists) 
else 
    //abc.get(8) will return a null pointer exception 

检查此链接其他方法上的ArrayList http://docs.oracle.com/javase/1.4.2/docs/api/java/util/ArrayList.html

1

isEmpty()功能是检查列表的大小检查整个数组列表是否为空。 你可能会拿起每个元素并检查。