英文:
Printing content of an Integer arraylist shows negative number at the end
问题
我创建了一个整数数组列表,并将0添加到10。当我尝试在for循环中打印它时,它打印出数组列表的最后一个元素为负1。
对Java很新手
import java.util.ArrayList;
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.get(i));
}
}
}
英文:
I created an integer arraylist and added 0 to 10 into it. when I try to print in a for loop it prints negative 1 as the last element of the arraylist.
New to 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));
}
}
}
答案1
得分: 2
因为您使用的是<=
,而不是<
。在您添加元素后,您的avarlist
将具有大小为11的大小。然后您会在列表上迭代12次(从0到11,包括边界)。
请记住:列表的最后一个索引始终是size() - 1
。当在列表上进行迭代时,几乎肯定需要使用< size()
。
英文:
Because you are using <=
instead of <
. Your avarlist
will have size 11 after you have added the elements. Then you iterate 12 times (from 0 to 11 inclusive) over the list.
Remember: the last index of a list is always size() - 1
. When iterating over a list, you almost certainly need to use < size()
.
答案2
得分: 1
使用for-each循环可以遍历您的ArrayList:
for (Integer i : avarlist) {
System.out.println(i);
}
英文:
Question is already answered, however you can improve your code:
For iterating through your ArrayList you can use for-each:
for(Integer i:avarlist){
System.out.println(i);
}
答案3
得分: 0
因为你正在使用 for 循环的终止条件为 i<= avarlist.size()
。在大多数编程语言中,数组或 ArrayList 的索引从 0 开始。所以你的最后一个元素的索引值应为 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) { // 使用增强型 for 循环
System.out.println(index);
index++;
}
英文:
Because you are using the terminating condition of the for loop as i<= avarlist.size()
. In a Array or ArrayList in most programming languages indexing starts from 0 .So your last element's index value is equals to avarlist.size() -1 .So refactor your code like one of the ways below.
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++;
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论