java - Copy objects into arraylist instead of pointing -


i trying create arraylist of nodes used come 1 place(node) another. nick name of place , node's pi previous node in path.

arraylist<node> bestway = new arraylist<node>(); while(chosen.nick != from){     bestway.add(chosen);     chosen = chosen.pi; } 

the problem elements in bestway becomes same. when print bestway place1, place1, place1, place1, , not place1, place2, place3, place4.

is possible copy elements array, , not add pointers chosen-element changes on line after. lot!

here example trying mimic explained. works me hence, error should somewhere else guess:

public class example {      public static void main(string[] args) {         list<node> bestway = new arraylist<node>();         node chosen = new node("place1");         string = 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] 

Comments

Popular posts from this blog

java - Intellij Synchronizing output directories .. -

git - Initial Commit: "fatal: could not create leading directories of ..." -