Pergunta

I have a set with String and i want to create hash map with String key and Node Object value. and this is my code

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);
            }

my problem is when i read first from c iterator and correctly make new object and put it to hash map but when second object was create in my hash map the previous object value was change like this

first read key = "New York" Value = Node (and the value of node is New York)

second read Key = "Los Angles" Value = Node (and the value of node is Los Angles) and my first read Value with New York key was change to Los Angles.

myNode class

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;
}

}

Please help me.

Foi útil?

Solução

That's because you made the city (and pathCost) fields static. A static field belongs to the class, not to a specific instance of this class. Each node has a specific city, so you want to mek the city field an instance field, and not a static field.

Read the Java tutorial about class members.

Outras dicas

The city member in your Node class is static. This means all the Nodes share the same city, and when one instance updates it (e.g., in the constructor), the change applies for all of them.

To resolve this issue, you could change city to be an instance member:

public class Node{
    private String city;
    ...

Without looking thoroughly there is a major mistake here:

private static String city;

city is node (i.e. instance) data and should not be static.

Since it is static in your case, all nodes share one value for city, which most probably isn't what you want. The same applies to pathCost.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top