1

I have an ArrayList which has objects of Coords which are x and y:

ArrayList<Coords> positionsArrayList = new ArrayList<>(values);

class Coords {
    int x;
    int y;

    public boolean equals(Object o) {
        Coords c = (Coords) o;
        return c.x == x && c.y == y;
    }

    public Coords(int x, int y) {
        super();
        this.x = x;
        this.y = y;
    }

    public int hashCode() {
        return new Integer(x + "0" + y);
    }
}

Now i want to extract this x and y in form of 2D array double[][]. Just like

double[][] vector={{0,0},{1,1},{2,2}}

I have tried this code:

for (Coords value : positionsArrayList) {
    positions = new double[][]{{value.x, value.y}};
}

But it does enter only the last entry. New to java please help

0

3 Answers 3

2

The statement:

positions = new double[][]{{value.x, value.y}};

reassigns the reference each time. Finally, positions will "point to" (contain) the last tuple, that's why you see it as the result.

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

Comments

1

What you can do is use traditional for loop to achieve the result:

positions = new double[positionsArrayList.size()][2];
for(int i =0; i < positionsArrayList.size(); i++){
    positions[i][0] = positionsArrayList.get(i).getX();
    positions[i][1] = positionsArrayList.get(i).getY();
}

Comments

1

You could assign each coordinates value for each index like:

double[][] positions = new double[positionsArrayList.size()][2];

for (int i = 0; i < positionsArrayList.size(); i++) {
    positions[i][0] = positionsArrayList.get(i).x;
    positions[i][1] = positionsArrayList.get(i).y;
}

Or if you're familiar with stream:

double[][] positions= positionsArrayList.stream()
            .map(coords -> new double[]{coords.x, coords.y})
            .toArray(double[][]::new);

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.