Reputation:
I am new to Java and trying to get the shortest path between several cities.
Start
at some point (city) got through all
the other cities and end
at the same city
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 },
output
could be the optimal route is City1--> City3--> City2 --> City4 ....My issue and question is is how to implement the City class that, any suggestions?
Upvotes: 0
Views: 368
Reputation: 27986
Ignoring the title of the question and answering your actual question directly:
City
. It seems the class is intended to represent a city rather than an arbitrary point.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