首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >我如何将其转换为Java,比如使用Maps

我如何将其转换为Java,比如使用Maps
EN

Stack Overflow用户
提问于 2018-10-15 08:41:04
回答 1查看 53关注 0票数 -2

我为我的任务选择了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"));
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 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);
    }

}

请记住,在面向对象语言中,利用可用的结构可以使您的工作变得更简单

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52808364

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档