![](/img/trans.png)
[英]How to get values from an array and store it into separate variables using java?
[英]How to get the known values of variables I store in a Java Object?
我讀取了 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;
}
一種解決方案是在 Geometry 對象內存儲 Coordinate 對象的數組,甚至是 Collection。 如果你還沒有使用Gson看看它,它會讓你的生活變得非常簡單。
class Coordinate {
private final double x;
private final double y;
public Coordinate(double x, double y) {
this.x = x;
this.y = y;
}
public double getX() {
return x;
}
public double getY() {
return y;
}
}
public class Geometry {
private final Collection<Coordinate> coordinates;
private final String type;
public Geometry(Collection<Coordinate> coordinates, String type) {
this.coordinates = coordinates;
this.type = type;
}
public Collection<Coordinate> getCoordinates() {
return coordinates;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.