简体   繁体   English

二维ArrayList错误

[英]Two dimensional ArrayList error

I am here trying to get an element from my two dimensional ArrayList but getting IndexOutOfBoundException error. 我在这里试图从我的二维ArrayList获取一个元素但是得到IndexOutOfBoundException错误。 What am I doing wrong here? 我在这做错了什么? Do I need to allocate the space like in a simple Array first? 我是否需要先在一个简单的数组中分配空间? If so, How can I do it in two dimensional array? 如果是这样,我怎么能用二维数组呢? Below is the code, 下面是代码,

import java.util.ArrayList;

public class Test {
    private ArrayList<ArrayList<String>> array;

    public Test(){
        array = new ArrayList<ArrayList<String>>();
        array.get(0).set(0, "00");
        array.get(0).set(1, "01");
        array.get(0).set(2, "02");
        array.get(1).set(0, "10");
        array.get(1).set(1, "11");
        array.get(1).set(2, "12");
        array.get(2).set(0, "20");
        array.get(2).set(1, "21");
        array.get(2).set(2, "22");
    }

    public String getE(int a, int b){
        return array.get(a).get(b);
    }

    public static void main(String[] args) {
        Test object = new Test();
        System.out.println(object.getE(0, 0)); // This gives me the error.
    }
}

You need to initialize the ArrayList s before you insert into them. 在插入ArrayList之前,需要初始化ArrayList Like this: 像这样:

public Test(){
    array = new ArrayList<ArrayList<String>>();
    array.add(new ArrayList<String>());
    array.add(new ArrayList<String>());
    array.add(new ArrayList<String>());
    array.get(0).add("00");
    array.get(0).add("01");
    array.get(0).add("02");
    array.get(1).add("10");
    array.get(1).add("11");
    array.get(1).add("12");
    array.get(2).add("20");
    array.get(2).add("21");
    array.get(2).add("22");
}

Right now, array is empty, so calling array.get(0) will result in the IndexOutOfBoundException . 现在, array为空,因此调用array.get(0)将导致IndexOutOfBoundException Once you add an initialized ArrayList at index 0, you will no longer get that error. 在索引0处添加初始化的ArrayList后,您将不再收到该错误。

The constructor ArrayList<ArrayList<String>>() makes an empty ArrayList<ArrayList<String>> . 构造函数ArrayList<ArrayList<String>>()使空ArrayList<ArrayList<String>> It does not initialize the contents of array ; 它不初始化array的内容; you need to do that yourself. 你需要自己做。

Additionally, using set(int i , E e) gives you the same problem if there is not already an element at index i. 另外,如果在索引i处还没有元素,则使用set(int i , E e)会给出相同的问题。 You should use add(E e) instead. 你应该使用add(E e)代替。 You can read more about set() at http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html#set(int , E). 您可以在http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html#set(int,E set()上阅读有关set()更多信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM