简体   繁体   中英

Two dimensional ArrayList error

I am here trying to get an element from my two dimensional ArrayList but getting IndexOutOfBoundException error. 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. 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 . Once you add an initialized ArrayList at index 0, you will no longer get that error.

The constructor ArrayList<ArrayList<String>>() makes an empty ArrayList<ArrayList<String>> . It does not initialize the contents of 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. You should use add(E e) instead. You can read more about set() at http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html#set(int , E).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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