猿问

我如何将其转换为 Java,也许使用 Maps

我为我的作业选择了一个 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"));


aluckdog
浏览 142回答 1
1回答

牧羊人nacy

基于您的原始概念...const cities = {&nbsp; NewYork: {&nbsp; &nbsp; route1: 'U',&nbsp; &nbsp; route2: 'C',&nbsp; &nbsp; direction: (x, y)=>{&nbsp; &nbsp; &nbsp; return {x:x+2, y:y*2};&nbsp; &nbsp; },&nbsp; },&nbsp; LosAngeles: {&nbsp; &nbsp; route1: 'U',&nbsp; &nbsp; route2: 'C',&nbsp; &nbsp; direction: (x, y)=>{&nbsp; &nbsp; &nbsp; return {x:x+2, y:y*2};&nbsp; &nbsp; },&nbsp; },};enum如果您想要一组无法更改的预定义值,我会使用 POJO(普通的旧 Java 对象)或者可能使用 POJO 。从一个Direction类开始,使这更简单......public class Direction {&nbsp; &nbsp; private int x;&nbsp; &nbsp; private int y;&nbsp; &nbsp; public Direction(int x, int y) {&nbsp; &nbsp; &nbsp; &nbsp; this.x = x;&nbsp; &nbsp; &nbsp; &nbsp; this.y = y;&nbsp; &nbsp; }&nbsp; &nbsp; public int getX() {&nbsp; &nbsp; &nbsp; &nbsp; return x;&nbsp; &nbsp; }&nbsp; &nbsp; public int getY() {&nbsp; &nbsp; &nbsp; &nbsp; return y;&nbsp; &nbsp; }}并且可能是 enumpublic enum City {&nbsp; &nbsp; NEW_YORK("U", "C"),&nbsp; &nbsp; LOS_ANGELES("U", "C");&nbsp; &nbsp; private String route1;&nbsp; &nbsp; private String route2;&nbsp; &nbsp; private Cities(String route1, String route2) {&nbsp; &nbsp; &nbsp; &nbsp; this.route1 = route1;&nbsp; &nbsp; &nbsp; &nbsp; this.route2 = route2;&nbsp; &nbsp; }&nbsp; &nbsp; public Direction direction(int x, int y) {&nbsp; &nbsp; &nbsp; &nbsp; return new Direction(x + 2, y * 2);&nbsp; &nbsp; }}现在,如果您需要能够在运行时创建不同的城市,您可能会考虑更像......public class City {&nbsp; &nbsp; private String route1;&nbsp; &nbsp; private String route2;&nbsp; &nbsp; private City(String route1, String route2) {&nbsp; &nbsp; &nbsp; &nbsp; this.route1 = route1;&nbsp; &nbsp; &nbsp; &nbsp; this.route2 = route2;&nbsp; &nbsp; }&nbsp; &nbsp; public String getRoute1() {&nbsp; &nbsp; &nbsp; &nbsp; return route1;&nbsp; &nbsp; }&nbsp; &nbsp; public String getRoute2() {&nbsp; &nbsp; &nbsp; &nbsp; return route2;&nbsp; &nbsp; }&nbsp; &nbsp; public Direction direction(int x, int y) {&nbsp; &nbsp; &nbsp; &nbsp; return new Direction(x + 2, y * 2);&nbsp; &nbsp; }}请记住,您使用 OO 语言时,请利用可用的构造使您的生活更简单
随时随地看视频慕课网APP

相关分类

Java
我要回答