Java:迭代不一致的列表对象

Java:迭代不一致的列表对象,java,Java,我正试图从一个对象的大小不等的数组中显示数组列表索引。如何迭代内部大小不一致的arraylist以防止IndexOutOfBoundsException public static void main(String[] args) { Hello b = new Hello(); System.out.println("test 1 =" +b.Apple().get(0)); System.out.println("test 2 =" +b.Apple().get(1)); System.o

我正试图从一个对象的大小不等的数组中显示数组列表索引。如何迭代内部大小不一致的arraylist以防止IndexOutOfBoundsException

public static void main(String[] args) {

Hello b = new Hello();
System.out.println("test 1 =" +b.Apple().get(0));
System.out.println("test 2 =" +b.Apple().get(1));
System.out.println("test 3 =" +b.Apple().get(2));

}
返回索引列表不一致结果的Hello.java文件

public ArrayList<Integer> Apple(){
ArrayList<Integer> values = new ArrayList<Integer>();

rs = db.getSM().executeQuery("SELECT a, b, count(*) AS rowCount from table");   
while(rs.next()) {
    values.add(rs.getInt("count"));
}

return values;
第二次运行时,它将有3个元素。所以它会打印出来

test 1 = 23
test 2 = 13
test 3 = 0
test 1 = 23
test 2 = 10
test 3 = 3    

如果您可以省略
测试3=0
的话,请在只有两个元素时提及示例解决方案:

for(int index=0; index<yourList.size(); index++) {
    Object element=yourList.get(index);
    // do something with the element (and its index if needed)
}
除了第一个提供索引的解决方案外,所有这些解决方案在功能上都是等效的

不要像我对元素类型所做的那样使用
Object
,显然应该使用元素的类型

要产生当前输出,第一个解决方案似乎最合适,因为它提供了一个索引:

ArrayList<Integer> yourList = b.Apple();
for (int index=0; index < yourList.size(); index++) {
    System.out.printf("test %d = %d", index + 1, yourList.get(index));
}

如果在第一次运行中未显示
test3=0
,您是否满意?如果未找到索引2,是否可以将其设为0?您应该将
Apple
转换为生成器通常的方法将省略
test3=0
并使用
作为受列表大小限制的循环,一个
迭代器
集合。我需要做嵌套for循环吗?非常感谢=)我知道了
Iterator<Object> it = yourList.iterator();
while (it.hasNext()) {
    Object element = it.next();
    //do something with your element
}
yourList.forEach(element -> /* do something with your element */);
ArrayList<Integer> yourList = b.Apple();
for (int index=0; index < yourList.size(); index++) {
    System.out.printf("test %d = %d", index + 1, yourList.get(index));
}
ArrayList<Integer> yourList = b.Apple();
int desiredSize=3;
int missingZeroes = desiredSize - yourList.size();
for(int addedZeroes=0; addedZeroes < missingZeroes; addedZeroes++) {
    yourList.add(0);
}
//then proceed with the above List traversal solutions.