【问题标题】:Getting IndexOutOfBoundException获取 IndexOutOfBoundException
【发布时间】:2014-09-10 21:43:39
【问题描述】:

为什么下面的 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);
}

【问题讨论】:

    标签: java indexoutofboundsexception


    【解决方案1】:

    List 维护插入顺序。 我们试图在索引 1 处添加一个元素,当列表为空时,这就是为什么它会导致 java.lang.IndexOutOfBoundsException: Index: 1, Size: 0

    快速解决方案:-

    1. 使用 Collection 接口的 add() 方法在列表中添加元素。

    列表列表 = new ArrayList();

    list.add(1);

    list.add(2);

    1. 使用 List 接口的 add(int index, T t) 方法将元素添加到列表中。 List list = new ArrayList();

    list.add(0, 1); // 用值 1 填充第 0 个索引。

    list.add(1, 2); // 用值 2 填充第 1 个索引。

    【讨论】:

      【解决方案2】:

      当 ArrayList 为空时,您不能在索引 1 处添加元素。它从 0 开始,或者直接使用 add。

      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

      投掷:

        IndexOutOfBoundsException - if the index is out of range 
        (index < 0 || index > size())
      

      当 size == 0 时,索引 1 超出范围。

      【讨论】:

        【解决方案3】:

        问题来了:

        list.add(1, 2);
        

        要修复它,请执行以下操作:

        list.add(0, 2);
        

        或者更简单,这个:

        list.add(2);
        

        请记住:在 Java 中,列出从索引 0 开始的数组,如果您尝试在空列表中添加索引为 1 的元素,则会出错。

        【讨论】:

          猜你喜欢
          • 2016-11-07
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-03-25
          • 2016-09-15
          • 2016-11-03
          • 1970-01-01
          相关资源
          最近更新 更多