Question

I am trying to write simple code which swaps elements in a Vector (there are other irrelevant lines in the method for other purposes so please ignore them). However when I call Collections.swap(clone1, 6,3) it changes "v" vector as well!! What did I do wrong??

The Method:

public static String DFS(Vector v){

            Vector clone1 = new Vector();
            clone1 = v;
            Vector clone2 = new Vector();
            clone2 = v;


            // In order to compare goal is reached or not I created a goal vector
            Vector solution = new Vector(9,0);
            for(int i = 0; i < 9; i++)
                    solution.addElement(i);


            if(v.isEmpty()){
                    return "Empty!!";
            }
            if(v.equals(solution)){
                    return "Solution!!!";
            }

            // In order to determine where the blank is
            int indexOfZero = 0;

            // Since this Depth-First Search, I am using stack as frontier
            Stack s = new Stack();


            indexOfZero = v.indexOf('0');

            if (indexOfZero == 6){
                            Collections.swap(clone1,6,3);
                            Collections.swap(clone2,6,7);
            }

            //for(int i = 0; i < list.size(); i++){
            //      s.push(list.get(i));
            //      System.out.println("Stack in for loop");
            //}

            //Vector a = (Vector)s.pop();
            System.out.println("\nElements after DFS:");
                    System.out.println(v.toString());
                    System.out.print("THIS IS MY ClONE 1: ");
                    System.out.println(clone1.toString());
                    System.out.print("THIS IS MY ClONE 2: ");
                    System.out.println(clone2.toString());
            System.out.println();
            return "a";
    }
Was it helpful?

Solution

You declared your references clone1 and clone2 to refer to the same object as v (and discarded the new Vector()s that were just created).

Using the assignment operator = with an object doesn't clone the object; it just makes another reference to refer to the same object.

v ----> Vector object
         ^
clone1 --+

You can create copies of your Vector by saying

Vector clone1 = new Vector(v);

Visually...

v ----> Vector object

clone1 ----> Cloned Vector object
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top