user7717824
user7717824

Reputation:

The optimal path in Java (tsp)

I am new to Java and trying to get the shortest path between several cities.

Parsing the date from JSON File:

{ "city": "City1", "latitude": 43.1641506, "longitude": 19.7600896 },
{ "city": "City2", "latitude": 60.4317477, "longitude": 10.0853171 },
{ "city": "City3", "latitude": 21.4317477, "longitude": 16.1854121 },

My issue and question is is how to implement the City class that, any suggestions?

Upvotes: 0

Views: 368

Answers (1)

sprinter
sprinter

Reputation: 27986

Ignoring the title of the question and answering your actual question directly:

  • I would suggest changing the name to City. It seems the class is intended to represent a city rather than an arbitrary point.
  • Unless there is some reason to expose the latitude and longitude through getters then I suggest not doing that. Better to encapsulate them in their own immutable class and have any logic to do with positions inside that class.

So I would suggest something like:

public class Position {
    private final double latitude;
    private final double longitude;

    public Position(double latitude, double longitude) {
        this.latitude = latitude;
        this.longitude = longitude;
    }

    public double distanceTo(Position other) {
        ...
    }
}

public class City {
    private final String name;
    private final Position position;

    public City(String name, double latitude, double longitude) {
        this.name = name;
        this.position = new Position(latitude, longitude);
    }

    public double distanceTo(City other) {
        return this.position.distanceTo(other.position);
    }
}

Those are clean simple classes that have a single purpose which will make your code easier to read and easier to change. They are also immutable (i.e. none of their values change after construction) which has lots of advantages (see answers to this question for details).

Upvotes: 2

Related Questions