【问题标题】:how to get an instance of an arraylist which is inside another arraylist如何获取另一个arraylist中的arraylist的实例
【发布时间】:2017-07-02 12:42:52
【问题描述】:

我在数组列表(嵌套数组列表)中有一个数组列表,如下所示

  ArrayList<ArrayList<Integer>> indexOfJSONObject = new ArrayList<ArrayList<Integer>>();

现在我需要获取arraylist 的一个实例,该实例存在于indexOfJSONObject 数组列表的给定索引中,并为其添加一个值。我使用了以下代码

    ArrayList<Integer> tempJSONObjectAL= (ArrayList<Integer>)indexOfJSONObject.get(givenIndex);

    tempJSONObjectAL.add(value); 

但它给了我的错误

线程“主”java.lang.IndexOutOfBoundsException 中的异常:索引:0,大小:0

如何解决这个问题以及为什么会发生这种情况。

谢谢

【问题讨论】:

  • 不难理解错误:您想要索引处的元素 0 ,所以第一个但列表为空:size = 0 您显然没有向 indexOfJSONObject 提供任何数据
  • 发生这种情况是因为indexOfJSONObject 不包含任何项目,并且每个文档规范在空列表上调用get 会导致IndexOutOfBoundsException
  • indexOfJSONObject 在您调用它时为空
  • 我猜你在arrayList的第一个位置基本上没有任何东西:-)这基本上就是你得到错误IOOBE的原因。由于将空数组列表添加到数组列表没有任何意义 - 因为第一个元素将是一个空对象 :-) 但是,如果您先 new ArrayList ,然后再添加一个新的 ArrayList ,事情将作为打算:-)。
  • 也许使用Map&lt;Integer, List&lt;Integer&gt;&gt;会更方便和可读

标签: java arraylist indexoutofboundsexception


【解决方案1】:

这里的问题似乎是列表大小为 0,而您仍在尝试访问位置 0 处的元素。

您不应该尝试直接访问集合中的元素,而不使用循环/迭代器或不检查比较大小和给定索引。您的代码应该类似于

ArrayList<Integer> tempJSONObjectAL= null;
if(indexOfJSONObject.size() > givenIndex)
    tempJSONObjectAL = (ArrayList<Integer>)indexOfJSONObject.get(givenIndex);

【讨论】:

    【解决方案2】:

    试试下面的代码:

    ArrayList<ArrayList<Integer>> indexOfJSONObject = new ArrayList<ArrayList<Integer>>();
            ArrayList<Integer> tempJSONObjectAL=new ArrayList<Integer>();
    
            for(ArrayList<Integer> list:indexOfJSONObject)
            {
                tempJSONObjectAL.add(list.get(index));
    
            }
    

    【讨论】:

      【解决方案3】:

      原因这很简单。此错误是因为indexOfJSONObject 是一个 ArrayList,它本身包含一个 ArrayList。但是您在 indexOfJSONObject 中没有任何 ArrayList。
      您最初是从 indexOfJSONObject 获取 ArrayList,而其中没有 ArrayList 实例化。
      您需要向 indexOfJSONObject 添加一个新的 ArrayList 实例化,然后使用它。

      通过添加一个特定的语句将解决该问题。只需检查下面的代码:

      ArrayList<ArrayList<Integer>> indexOfJSONObject = new ArrayList<ArrayList<Integer>>();
      
      //This line of code is required in your case
      indexOfJSONObject.add(new ArrayList<Integer>());
      
      ArrayList<Integer> tempJSONObjectAL= (ArrayList<Integer>)indexOfJSONObject.get(givenIndex);
      
      tempJSONObjectAL.add(value); 
      

      【讨论】:

        猜你喜欢
        • 2019-06-20
        • 2021-08-07
        • 1970-01-01
        • 1970-01-01
        • 2022-06-12
        • 1970-01-01
        • 1970-01-01
        • 2020-07-21
        • 1970-01-01
        相关资源
        最近更新 更多