下午好。
我有一个City类,它接收到其他City对象的距离值不同。
但是,在创建城市并添加距离之后,每个城市都会获得相同的距离值,这是上一次添加的城市的值。
也就是说,运行后,cityA.toString的输出应为{B = 5,C = 4,D = 7,E = 6,F = 5,G = 7,H = 4,I = 2, J = 9},而不是{A = 6,B = 5,C = 5,D = 6,E = 4,F = 8,G = 5,H = 4,I = 3,J = 8}
您知道我在做什么错吗?谢谢
public class City {
private String name;
private static HashMap<String, Integer> distancias;
public City(String name){
this.name = name;
distancias = new HashMap<String, Integer>();
}
public void insertDistances(City city, int dist) {
distancias.put(city.getName(), dist);
}
public static void main(String[] args) {
City cityA = new City("A");
City cityB = new City("B");
City cityC = new City("C");
City cityD = new City("D");
City cityE = new City("E");
City cityF = new City("F");
City cityG = new City("G");
City cityH = new City("H");
City cityI = new City("I");
City cityJ = new City("J");
cityA.insertDistances(cityB, 5);
cityA.insertDistances(cityC, 4);
cityA.insertDistances(cityD, 7);
cityA.insertDistances(cityE, 6);
cityA.insertDistances(cityF, 5);
cityA.insertDistances(cityG, 7);
cityA.insertDistances(cityH, 4);
cityA.insertDistances(cityI, 2);
cityA.insertDistances(cityJ, 9);
cityB.insertDistances(cityA, 6);
cityB.insertDistances(cityC, 5);
cityB.insertDistances(cityD, 6);
cityB.insertDistances(cityE, 4);
cityB.insertDistances(cityF, 8);
cityB.insertDistances(cityG, 5);
cityB.insertDistances(cityH, 4);
cityB.insertDistances(cityI, 3);
cityB.insertDistances(cityJ, 8);
}
}
答案 0 :(得分:0)
private static HashMap<String, Integer> distancias;
删除静态
改为使用private HashMap<String, Integer> distancias
`
静态变量是类的所有实例(或对象)所共有的,因为它是类级别的变量。