猿问

如何将 Arraylist 转换为 2D 双[][] 数组

我有一个具有s的对象,它们是x和y:ArrayListCoord


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);

    }

}

现在我想以2D数组的形式提取这个x和y。就像double[][]


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


我试过这个代码:


for (Coords value : positionsArrayList) {

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

}

但它确实只输入最后一个条目。Java新手请帮忙


慕姐8265434
浏览 95回答 3
3回答

ibeautiful

声明:positions&nbsp;=&nbsp;new&nbsp;double[][]{{value.x,&nbsp;value.y}};每次重新分配引用。最后,将“指向”(包含)最后一个元组,这就是为什么你把它看作是结果。positions

慕田峪4524236

您可以做的是使用传统的 for 循环来实现结果:positions = new double[positionsArrayList.size()][2];for(int i =0; i < positionsArrayList.size(); i++){&nbsp; &nbsp; positions[i][0] = positionsArrayList.get(i).getX();&nbsp; &nbsp; positions[i][1] = positionsArrayList.get(i).getY();}

慕盖茨4494581

您可以为每个索引分配每个坐标值,例如:double[][] positions = new double[positionsArrayList.size()][2];for (int i = 0; i < positionsArrayList.size(); i++) {&nbsp; &nbsp; positions[i][0] = positionsArrayList.get(i).x;&nbsp; &nbsp; positions[i][1] = positionsArrayList.get(i).y;}或者,如果您熟悉直播:double[][] positions= positionsArrayList.stream()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .map(coords -> new double[]{coords.x, coords.y})&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .toArray(double[][]::new);
随时随地看视频慕课网APP

相关分类

Java
我要回答