[英]Printing content of an Integer arraylist shows negative number at the end
I created an integer arraylist and added 0 to 10 into it.我创建了一个整数数组列表并将 0 到 10 添加到其中。 when I try to print in a for loop it prints negative 1 as the last element of the arraylist.当我尝试在 for 循环中打印时,它将负 1 打印为数组列表的最后一个元素。
New to java Java 新手
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class StudentList {
public static void main(String[] args) {
List<Integer> avarlist = new ArrayList<>();
for (int i=0; i<=10; i++){
avarlist.add(i);
}
for (int i= 0; i<= avarlist.size(); i++){
System.out.println(avarlist.indexOf(i));
}
}
}
Because you are using <=
instead of <
.因为您使用的是<=
而不是<
。 Your avarlist
will have size 11 after you have added the elements.添加元素后,您的avarlist
大小将是 11。 Then you iterate 12 times (from 0 to 11 inclusive) over the list.然后在列表上迭代 12 次(从 0 到 11 次)。
Remember: the last index of a list is always size() - 1
.请记住:列表的最后一个索引始终是size() - 1
。 When iterating over a list, you almost certainly need to use < size()
.在迭代列表时,您几乎肯定需要使用< size()
。
Question is already answered, however you can improve your code:问题已经得到解答,但是您可以改进您的代码:
For iterating through your ArrayList you can use for-each:要遍历您的 ArrayList,您可以使用 for-each:
for(Integer i:avarlist){
System.out.println(i);
}
Because you are using the terminating condition of the for loop as i<= avarlist.size()
.因为您将 for 循环的终止条件用作i<= avarlist.size()
。 In a Array or ArrayList in most programming languages indexing starts from 0 .在大多数编程语言的 Array 或 ArrayList 中,索引从 0 开始。 So your last element's index value is equals to avarlist.size() -1 .So refactor your code like one of the ways below.所以你的最后一个元素的索引值等于 avarlist.size() -1 。所以像下面的方法之一重构你的代码。
for (int i= 0; i < avarlist.size(); i++){
System.out.println(avarlist.indexOf(i));
}
for (int i= 0; i <= avarlist.size()-1; i++){
System.out.println(avarlist.indexOf(i));
}
int index =0;
for(int i :avarlist){//Using an enhanced for loop
System.out.println(index);
index++;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.