Question

I am trying to create an arraylist of the nodes used to come from one place(node) to another. The nick is the name of the place and a Node's pi is the previous node in the path.

ArrayList<Node> bestWay = new ArrayList<Node>();
while(chosen.nick != from){
    bestWay.add(chosen);
    chosen = chosen.pi;
}

The problem is that all the elements in bestWay becomes the same. When I print bestWay I just get PLACE1, PLACE1, PLACE1, PLACE1, and not PLACE1, PLACE2, PLACE3, PLACE4.

Is it possible to copy the elements into the array, and not add pointers to the chosen-element which changes on the line after. Thanks a lot!

Was it helpful?

Solution

Here is an example trying to mimic what you explained. It works for me hence, the error should be somewhere else i guess:

public class Example {

    public static void main(String[] args) {
        List<Node> bestWay = new ArrayList<Node>();
        Node chosen = new Node("Place1");
        String from = chosen
                .add("Place2")
                .add("Place3")
                .add("Place4")
                .add("Place5")
                .nick;
        while (chosen.nick != from) {
            bestWay.add(chosen);
            chosen = chosen.pi;
        }
        System.out.println(bestWay);
    }
}

class Node {

    final String nick;
    Node pi;

    Node(String nick) { this.nick = nick; }

    public Node add(String nick) {
        pi = new Node(nick);
        return pi;
    }

    @Override public String toString() {
        return nick;
    }
}

OUTPUT:

[Place1, Place2, Place3, Place4]

OTHER TIPS

so I'd put this in a comment, but my rep isn't high enough. I had a similiar problem in C# a while back and I think the problem was solved by instantiating a new list component variable inside the loop. Not promising it will work but it's worth a try. Something like

ArrayList<Node> bestWay = new ArrayList<Node>();
  while(chosen.nick != from){
  Node dummy = new Node();
  dummy = chosen;

  bestWay.add(dummy);
  chosen = chosen.pi;      
}

Inside while, the first line: bestWay.add(chosen); adds a record to bestWay.

After this you have done: chosen = chosen.pi; this changes the reference of chosen object to the reference of chosen.pi, so this also changes the value you added to the arraylist bestway. That is the reason you are getting same value in arraylist.

If your Node class can be cloned then you can do the following:

ArrayList<Node> bestWay = new ArrayList<Node>();
while(chosen.nick != from){
    bestWay.add(chosen);
    chosen = chosen.pi.clone();
}

or this:

ArrayList<Node> bestWay = new ArrayList<Node>();
while(chosen.nick != from){
    bestWay.add(chosen.clone());
    chosen = chosen.pi;
}

if the Node class is not clonable yet, then you can write your custom code for clone by overridding clone method in the Node class.

hope this helps

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top