我有一个字符串集,我想用字符串键和节点对象值创建散列映射。 这是我的代码
Set<String> cities = new HashSet<>();
Map<String, Node> allCity = new HashMap<>();
Iterator<String> c = cities.iterator();
while(c.hasNext()){
String name = c.next();
Node cit = new Node(name);
allCity.put(name, cit);
}
我的问题是,当我首先从 c 迭代器读取并正确地创建新对象并将其放入 HashMap 时,但是当在我的 HashMap 中创建第二个对象时,先前的对象值会像这样更改
初读 键=“纽约” Value = Node(node的值为New York)
二读 键 = "洛杉矶" 值 = 节点(节点的值为 Los Angles) 我第一次阅读 Value with New York key 是更改为 Los Angles。
我的节点类
public class Node{
private static String city;
private static double pathCost;
private ArrayList<Edge> neighbours;
private Node parent;
public Node(String cityName){
city = cityName;
neighbours = new ArrayList<>();
}
public static String getValue() {
return city;
}
public static void setValue(String city) {
Node.city = city;
}
public static double getPathCost() {
return pathCost;
}
public static void setPathCost(double pathCost) {
Node.pathCost = pathCost;
}
public static String getCity() {
return city;
}
public static void setCity(String city) {
Node.city = city;
}
public ArrayList<Edge> getNeighbours() {
return neighbours;
}
public void setNeighbours(ArrayList<Edge> neighbours) {
this.neighbours = neighbours;
}
public void addNeighbours(Edge n){
this.neighbours.add(n);
}
public Node getParent() {
return parent;
}
public void setParent(Node parent) {
this.parent = parent;
}
@Override
public String toString() {
return city;
}
请帮帮我。
最佳答案
那是因为您将 city
(和 pathCost
)字段设置为 static
。静态字段属于类,而不属于此类的特定实例。每个节点都有一个特定的城市,因此您希望将城市字段设置为实例字段,而不是静态字段。
关于java - HashMap 改变 Values 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23471451/