Java:迭代列表对象不一致



我正在尝试显示从对象的数组大小的数组大小的数组列表。如何迭代一个尺寸不一致以防止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;

预期结果

第一次运行,它只有2个元素。因此它将打印

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

第二次运行,它将具有3个元素。因此它将打印

test 1 = 23
test 2 = 10
test 3 = 3    

示例解决方案如果只有两个元素,则可以省略test 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)
}
for(Object element : yourList) {
    //do something with the element
}
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 */);

除了提供索引的第一个解决方案外,所有这些解决方案在功能上都是等效的。

不要像我对元素类型一样使用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));
}

(printf采用一个字符串模板和此模板的参数列表;此处%d代表数字,第一个事件由1个基于1的索引代替,第二个事件由列表元素的值替换(

( (

如果您不想省略test 3 = 0输出,我认为Federico Klez Culloca的创建生成器的建议是最好的,但是由于我不熟悉它们直到达到目标大小:

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.

最新更新