[英]HashMap change Values Object
我有一个String集合,我想用String键和Node Object值创建哈希映射。 这是我的代码
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迭代器读取并正确创建新对象并将其放入哈希映射时,但是当我在哈希映射中创建第二个对象时,先前的对象值会像这样更改
第一个读取键=“纽约”值=节点(节点的值为纽约)
第二次读取的Key =“ Los Angles”值=节点(节点的值为Los Angles),而我对纽约键的第一个读取的Value是更改为Los Angles。
myNode类
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;
}
}
请帮我。
您的Node
类中的city
成员是static
。 这意味着所有 Node
共享同一个city
,并且当一个实例更新它(例如,在构造函数中)时,更改将应用于所有城市。
要解决此问题,您可以将city
更改为实例成员:
public class Node{
private String city;
...
如果不仔细看,这里有一个主要错误:
private static String city;
city
是节点(即实例)数据,不应为静态数据。
由于在您的情况下是静态的,因此所有节点都为city
共享一个值,这很可能不是您想要的。 同样适用于pathCost
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.