0

I have this defined: List<Integer[][]> listOfInteger= new ArrayList<>();

How do I insert data into it?

I have tried

listOfInteger.add(new Integer[][](1,2));

and

List<Integer[][]> listOfInteger= Arrays.asList(new Integer({1, 2)});

But none works

4
  • Don't mix lists and arrays. Either use a List<ArrayList<Integer>> or Integer [][] Commented Aug 1, 2015 at 21:09
  • @Reimeus I have a requirement that store an 2d array element into a list. Since List<> can't take int, i have to make it Integer Commented Aug 1, 2015 at 21:09
  • docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html. But you should create a class IMO. Commented Aug 1, 2015 at 21:11
  • listOfInteger.add(new Integer[][]{{1,2},{3,4}}); Commented Aug 1, 2015 at 21:12

3 Answers 3

2

Have you tried the "double brace initialization"?

List<Integer[][]> listOfInteger= new ArrayList() {{
    add(new Integer[][] { { 3, 2 }, { 4, 2 } });
    add(new Integer[][] { { 3, 2 }, { 4, 2 } });
    add(new Integer[][] { { 3, 2 }, { 4, 2 } });
}};

You can do this at the class level outside of methods.

Sign up to request clarification or add additional context in comments.

Comments

1

The short way is this:

listOfInteger.add(new Integer[][] {{1, 2}, {1, 3}, {5, 7}});

But you could also just create the array and then fill it one by one.

2 Comments

Any way to assign the value without calling the .add method? I am trying to initialize listOfInteger and give it values at the beginning of the class and outside of method blocks.
@HashMap is the list static? is this the problem? could use static initializer block static { } in there you can do the adds. Also works for static final, create temp list, add everything, assign to static final var.
1

You got confused by the dimensions you have defined an one dimensional ArrayLists which contains two-dimensional arrays as elements.

    List<Integer[][]> listOfInteger = new ArrayList<Integer[][]>();
    // long version
    Integer[][] array2d = new Integer[2][2];
    array2d[0][0] = 3;
    array2d[0][1] = 2;
    array2d[1][0] = 4;
    array2d[1][1] = 2;
    listOfInteger.add(array2d);
    // short version
    listOfInteger.add(new Integer[][] { { 3, 2 }, { 4, 2 } });

After this operations your arrayList will contain two arrays, which contain integers with the same value

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.