0

I have added some values to drawPoints[][] and then made an ArrayList Object points that is

ArrayList points=new ArrayList();
points.add(drawPoints);

Now i want to retrieve the value of drawPoints from points, how can i do that?

5 Answers 5

3

You need to access first drawPoints in your ArrayList with

int[][] tmp = (int[][]) points.get(0);

and then you will be able to get values with for example

tmp[0][1];

Here's a little example of a program that prints values of two 2D arrays that are stored in an ArrayList:

int[][] drawPoints = new int[2][2];
int[][] drawPoints2 = new int[2][2];
drawPoints[0][0] = 1;
drawPoints[0][1] = 2;
drawPoints[1][0] = 3;
drawPoints[1][1] = 4;
drawPoints2[0][0] = 5;
drawPoints2[0][1] = 6;
drawPoints2[1][0] = 7;
drawPoints2[1][1] = 8;
ArrayList<Object> points=new ArrayList<Object>();
points.add(drawPoints);
points.add(drawPoints2);

for(Object tab : points){
    int[][] tmp = (int[][]) tab;
    for(int i=0;i < tmp.length;i++){ 
        for(int j=0;j<tmp[i].length;j++){ 
            System.out.println(tmp[i][j]);
        }
    }
    System.out.println("------------");
}
Sign up to request clarification or add additional context in comments.

3 Comments

do i need to do something like this? <code>for(int i=0;i<points.size();i++){ for(int j=0;j<points.size();j++){ tmp[i][j]=(int[][])points.get(i); } </code> ???
@user1167744 what are you trying to achieve exactly?
@user1167744 see my edit, i stored two 2D arrays in an ArrayList, then I extract each tab, put in a tmp variable and print their values.
3

You just put a 2d array into the first slot of an ArrayList. So you'd write:

 int[][]somePoints = (int[][])points.get(0);

1 Comment

do i need to do some thing like this? for(int i=0;i<points.size();i++){ for(int j=0;j<points.size();j++){ tmp[i][j]=(int[][])points.get(i); } ??
0

if i understand correctly:

points.get(0); // get the first item (at index 0) from the list

1 Comment

wow you guys are quick, 3 comments while i was editing it ;) thanks.
0

An ArrayList is backed by a 1-dimensional array. If you want to mimic your drawPoints[][], I suggest using a ArrayList, then iterating over it to fill it, then retrieve the values.

Comments

0

points.get(i) gives you the value, in this case i = 0.

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.