How can I convert this to Java, perhaps using Maps

leggo

New Member
#1
I picked up a JS code for my assignment and I'm having problems achieving this in Java. My aim is to create predefined values of cities.
Mã:
* Removed JS code *
How can I convert this to Java, perhaps using Maps, I have an idea. i just don't know how to put this together perfectly.
Mã:
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"));
 

Admin

Administrator
Thành viên BQT
#2
Based on your original concept...
Mã:
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};
    },
  },
};
I would either use a POJO (plain old Java object) or possibly an enum if you want to have a predefined set of values which can't be changed.

Starting with a Direction class to make this simpler...
Mã:
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;
    }
}
And possibly an enum
Mã:
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);
    }

}
Now, if you need to be able to create different cities at runtime, you might consider something more like...
Mã:
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);
    }

}
Remember, your in a OO language, make use of the constructs available to you to make your life simpler
 
Top