- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
为什么下面的 main 方法在 list.add(1, 2) 处给出 IndexOutOfBoundException?
public static void main(String[] args) {
List<Integer> list = new ArrayList<Integer>();
list.add(1, 2);
int total = list.get(0);
System.out.println(total);
}
最佳答案
当 ArrayList 为空时,您不能在索引 1 处添加元素。它从 0 开始,或者只使用添加。
public static void main(String[] args) {
List<Integer> list = new ArrayList<Integer>();
list.add(1);
list.add(2);
int total = list.get(0); // <-- You even use 0 here!
System.out.println(total);
}
根据 ArrayList#add(int index, E element)
javadoc ,
Throws:
IndexOutOfBoundsException - if the index is out of range
(index < 0 || index > size())
当 size == 0 时,索引 1 超出范围。
关于java - 获取 IndexOutOfBoundException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24847257/
我在尝试按分隔符分割字符串时遇到了一些麻烦。一些示例输入是: 2@8:00AM 3 4@9:00AM@10:00AM 5@10:00AM@11:00AM@12:00PM 我想使用分隔符@分割字符串,将
我不知道我做错了什么,但我在我的应用程序中收到“IndexOutOfBoundException”。这是我的代码和 logcat: //代码 public class GameView extends
我编写了以下方法来返回网站上所有元素的对象。 public ArrayList getWantedFields() { log.info("retrieve wanted fields");
我使用此代码写入文件,它抛出 IndexOutOfBoundException。 InputStream is = res.openStream(); FileOutputStream fos = n
我遇到了一个小问题,我收到错误 java.lang.IndexOutOfBoundsException: Index: 29, Size: 29 当我启动此代码时,错误位于行 if ((listaSw
我有 5 个年份列表和 5 个与年份列表相对应的金额列表。 year_Earnings = [2011,2012,2013]; year_Expense = [2011,2012]; year_Inv
我有以下简单的类: public class Polynomial { private double[] c; public double get(int i) throws Inde
我不明白这是怎么回事 我在用 public class UrlArrayAdapter extends BaseAdapter {... ArrayList objec
为什么下面的 main 方法在 list.add(1, 2) 处给出 IndexOutOfBoundException? public static void main(String[] args)
我得到一个错误: Caused by: java.lang.IndexOutOfBoundsException: Index: 1, Size: 1 我认为下面的代码非常好!!任何指导将不胜感激 fo
如果我们创建一个如下所示的虚拟 ArrayList 并使用 -1 和 1 作为参数调用 get 方法。然后我们得到以下输出: 对于测试用例 1:它抛出 ArrayIndexOutOfBoundExce
我尝试使用以下代码将 pi 替换为 *pi,但是它引发了完全意外的异常。匹配器如何查看高于字符串长度的索引? private void makeEvaluationStringExpressionMX
我的代码 public List compute_polygon(List waypoints, double d) { int N = waypoints.s
我有一个具有以下结构的 csv 文件 Name | Val1 | Val2 | Val3 | Val4 | Val5 John 1 2 Joe 1 2 David
这个问题在这里已经有了答案: ArrayList initial capacity and IndexOutOfBoundsException [duplicate] (3 个答案) 关闭 6 年前
我正在制作一个将单位转换为不同单位的应用程序。我正在尝试使该应用程序在以下步骤中运行。 选择带有旋转器的类别(温度、长度等) 根据选择的类别,其他两个旋转器将显示属于每个类别的单位。 这是到目前为止的
这个问题在这里已经有了答案: ArrayList initial capacity and IndexOutOfBoundsException [duplicate] (3 个答案) 关闭 6 年前
我有一个像这样的 Wicket 页面: public final class Services extends WebPage { public Services() { su
您好,我正在尝试从回收器 View 中删除一个项目,但在成功删除后,当我滚动到底部时,应用程序崩溃并显示此错误。我尝试打电话 notifyItemRemoved(position); notifyIt
我对 Github 上 pakerfeldt 的 ViewFlow 类有疑问。 我正在尝试创建一个“不同的 View View 流”。这是我的 Activity 代码: package com.sun
我是一名优秀的程序员,十分优秀!