Data Element – Town (Vertex) Create a Town class that holds the name of the town
ID: 3817651 • Letter: D
Question
Data Element – Town (Vertex)
Create a Town class that holds the name of the town and a list of adjacent towns, and other fields as desired, and the traditional methods (constructors, getters/setters, toString, etc.). It will implement the Comparable interface. This is the class header:
public class Town implements Comparable<Town>
Two towns will be considered the same if their name is the same.
Data Element – Road (Edge)
Create a class Road that can represent the edges of a Graph of Towns. The class must implement Comparable. The class stores references to the two vertices(Town endpoints), the distance between vertices, and a name, and the traditional methods (constructors, getters/setters, toString, etc.), and a compareTo, which compares two Road objects. Since this is a undirected graph, an edge from A to B is equal to an edge from B to A. This is the class header:
public class Road implements Comparable<Road>
Explanation / Answer
import java.util.List;
public class Town implements Comparable<Town> {
private String Name;
public List<Town> AdjTowns;
//constructor
public Town(String Name, List<Town> AdjTowns) {
this.Name = Name;
this.AdjTowns = AdjTowns;
}
//constructor
public Town(String Name) {
this.Name = Name;
}
//getters and setters
public String getName() {
return Name;
}
public void setName(String Name) {
this.Name = Name;
}
public List<Town> getAdjTowns() {
return AdjTowns;
}
public void setAdjTowns(List<Town> AdjTowns) {
this.AdjTowns = AdjTowns;
}
//method to print the data
@Override
public String toString() {
return "Town{" + "Name=" + Name + ", AdjTowns=" + AdjTowns + '}';
}
//method to compare the data
@Override
public int compareTo(Town o) {
if (this.Name.equals(o.Name)) {
return 1;
} else {
return 0;
}
}
}
public class Road implements Comparable<Road> {
private Town t1, t2;
private String Name;
private int Distance;
//constructor
public Road(Town t1, Town t2, String Name, int Distance) {
this.t1 = t1;
this.t2 = t2;
this.Name = Name;
this.Distance = Distance;
}
//getters and setters
public Town getT1() {
return t1;
}
public void setT1(Town t1) {
this.t1 = t1;
}
public Town getT2() {
return t2;
}
public void setT2(Town t2) {
this.t2 = t2;
}
public String getName() {
return Name;
}
public void setName(String Name) {
this.Name = Name;
}
public int getDistance() {
return Distance;
}
public void setDistance(int Distance) {
this.Distance = Distance;
}
//method to compare the data
@Override
public int compareTo(Road o) {
if (this.Distance == (o.Distance)) {
return 1;
} else {
return 0;
}
}
//method to print the data
@Override
public String toString() {
return "Road{" + "t1=" + t1 + ", t2=" + t2 + ", Name=" + Name + ", Distance=" + Distance + '}';
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.