如何获得我存储在Java对象中的变量的已知值?

问题描述 投票:0回答:1

我读取JSON并将数据存储到不同的对象中。我在名为Geometry的类中存储了一些坐标。该类如下所示:

public class Geometry {

    private Object[] coordinates;
    private String type;

    public Object[] getCoordinates() {
        return coordinates;
    }
}

如您所见,coordinates字段是类Object的数组。

知道coordinates总是有2个位置(2个坐标),并且这些坐标的类型是double,如何获得坐标的double值?

更确切地说,对于系统显式返回两个坐标,我必须在以下方法上写些什么?

public double[] returnCoordinates() {
    double[] coord;

    coord[0] = //?
    coord[1] = //?

    return coord;
}
java object double
1个回答
0
投票

一种解决方案是将坐标对象的数组,甚至是集合存储在Geometry对象内。

class Coordinate {

    private final int x;

    private final int y;

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

    public int getX() {
        return x;
    }

    public int getY() {
        return y;
    }
}
public class Geometry {

    private final Coordinate[] coordinates;

    private final String type;

    public Geometry(Coordinate[] coordinates, String type) {
        this.coordinates == coordinates;
        this.type = type;
    }

    public Coordinate[] getCoordinates() {
        return coordinates;
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.