java - HashMap 改变 Values 对象

标签 java hashmap

我有一个字符串集,我想用字符串键和节点对象值创建散列映射。 这是我的代码

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 tutorial about class members .

关于java - HashMap 改变 Values 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23471451/

相关文章:

java - 我的 android 项目测试设置中缺少任何内容吗?

Java : How to remove all characters in String except a a-z, 数字和德语字符

java - 尝试使用第三个矩阵同时初始化两个矩阵 Row 和 Col

java - 在java中使用numberFormat.parse ("")方法时得到错误的输出

java - 试图比较两个迭代器的内容,怎么样?

java - 在 HashMap 中向 HashMap 添加元素

java - 在 Java 8 中使用 Lambda 将流收集到 HashMap

java - SharedPreferences get 总是返回默认值而不是实际值

java - 使用DFS回溯算法生成迷宫的问题

Java HashMap 逆向方式