我为我的任务选择了JS代码,但在Java中实现这一点时遇到了问题。我的目标是创造预定义的城市价值。
* Removed JS code *
我如何将其转换为Java,也许是使用Maps,我有一个想法。我只是不知道怎么把这一切完美地结合在一起。
Map<String, Object> routes = new TreeMap<>();
routes.put("route1", "U");
routes.put("route2", "C");
routes.put("direction", Object);
Map<String, Map<String, Object>> cities = new HasHMap<>();
cities.put("NewYork", routes.get("route1"));
cities.put("LosAngeles", routes.get("route2"));
发布于 2018-10-15 09:00:25
基于你最初的概念..。
const cities = {
NewYork: {
route1: 'U',
route2: 'C',
direction: (x, y)=>{
return {x:x+2, y:y*2};
},
},
LosAngeles: {
route1: 'U',
route2: 'C',
direction: (x, y)=>{
return {x:x+2, y:y*2};
},
},
};
我要么使用POJO (普通老Java对象),要么可能使用enum
,如果您想要一组不能更改的预定义的值。
从一个Direction
类开始,让这一切变得更简单……
public class Direction {
private int x;
private int y;
public Direction(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
}
可能还有一个enum
public enum City {
NEW_YORK("U", "C"),
LOS_ANGELES("U", "C");
private String route1;
private String route2;
private Cities(String route1, String route2) {
this.route1 = route1;
this.route2 = route2;
}
public Direction direction(int x, int y) {
return new Direction(x + 2, y * 2);
}
}
现在,如果您需要能够在运行时创建不同的城市,您可能会考虑更类似于...
public class City {
private String route1;
private String route2;
private City(String route1, String route2) {
this.route1 = route1;
this.route2 = route2;
}
public String getRoute1() {
return route1;
}
public String getRoute2() {
return route2;
}
public Direction direction(int x, int y) {
return new Direction(x + 2, y * 2);
}
}
请记住,在面向对象语言中,利用可用的结构可以使您的工作变得更简单
https://stackoverflow.com/questions/52808364
复制相似问题