Floose
Floose

Reputation: 535

copying two vectors java

I was trying to compile the following lines of code and got errors:

  public class c
  {
   vector<a> variables;
   void create_c(Vector<a> l)
   {    
     Vector<a> variables = new Vector<a>();
     variables.setSize(l.size()); // so that variables has enough capacity to store l
     /*variables= l.clone();*/
     Collections.copy(variables, l);
    }

   }

I'm trying to copy the contents of one vector to another by using the clone() method or Collections.copy() method. the in vector is actually another class having its own methods and variables.

 public class a
 {

 int a;
 void add_a(int y)
 {
 a=y;
 }

 }

While most people have suggested using Arraylist(), I'd like to implement this using Vector too and check for performance. So, I'd be happy if someone could give me a solution involving vectors.

The problem with the code is I'm getting an error saying 'Type mismatch: cannot convert from Object to Vector' at Collections.copy(variables,l). If I comment out the Collections.copy() and try it with the clone() statement in the next line, I'm getting the same error.

I must also mention that I class a is a public class having its own file in the same package.

What have I done wrong?

Upvotes: 1

Views: 2345

Answers (3)

Kerem
Kerem

Reputation: 1553

Vector newVector = (Vector) oldVector.clone();

Above code simply works for deep copying a vector.

Upvotes: 0

sunil
sunil

Reputation: 6604

First of all you need to take care of the following things

  • The compilation error with variables= l.clone() can be solved by casting to your Vector. Like this variables = (Vector<a>)l.clone() (btw, ignore the typecast warning)
  • The given code Collections.copy(variables, l); compiles just fine, without any errors
  • Try to use Java Naming Conventions always

The Collections.copy() gives you a shallow copy of your collection. Use the following example to make a deep copy of your collection.

  • Here the class that being copied should implement Cloneable interface and override the clone method
  • Iterate over the original collection and add the cloned objects to the target collection
  • the createCopy function returns the deep-copied collection
  • Notice the difference in memory locations of the copied and original vectors in the print statements in the console

The TestCopy class

package com.test;

import java.util.Vector;

public class TestCopy {

    private Vector<ClassToCopy> createCopy(Vector<ClassToCopy> classToCopy) {
        Vector<ClassToCopy> localVariable = new Vector<ClassToCopy>();
        for(ClassToCopy classVar:classToCopy)
            try {
                localVariable.add((ClassToCopy)classVar.clone());
            } catch (CloneNotSupportedException e) {
                e.printStackTrace();
            }
        return localVariable;
    }

    public static void main(String[] args) {

        Vector<ClassToCopy> originalVector = new Vector<ClassToCopy>();

        TestCopy testCopy = new TestCopy();
        originalVector.add(new ClassToCopy(1));
        originalVector.add(new ClassToCopy(2));
        originalVector.add(new ClassToCopy(3));
        originalVector.add(new ClassToCopy(4));
        System.out.println(originalVector);

        Vector<ClassToCopy> copiedVector = testCopy.createCopy(originalVector);
        System.out.println(copiedVector);

    }

}

The ClassToCopy class

package com.test;

public class ClassToCopy implements Cloneable {

    private int varA;

    /**
     * Constructor for ClassToCopy.
     * @param varA <tt></tt>
     */
    public ClassToCopy() {
        this(-1);
    }

    /**
     * Constructor for ClassToCopy.
     * @param varA <tt></tt>
     */
    public ClassToCopy(int varA) {
        super();
        this.varA = varA;
    }

    /**
     * Gets the varA.
     * 
     * @return <tt> the varA.</tt>
     */
    public int getVarA() {
        return varA;
    }

    /**
     * Sets the varA.
     *
     * @param varA <tt> the varA to set.</tt>
     */
    public void setVarA(int varA) {
        this.varA = varA;
    }

    /* (non-Javadoc)
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        return "ClassToCopy : "+super.toString()+" [varA=" + varA + "]";
    }

    /* (non-Javadoc)
     * @see java.lang.Object#clone()
     */
    @Override
    protected Object clone() throws CloneNotSupportedException {
        // TODO Auto-generated method stub
        return super.clone();
    }

}

The output i got

[ClassToCopy : com.test.ClassToCopy@19821f [varA=1], ClassToCopy : com.test.ClassToCopy@addbf1 [varA=2], ClassToCopy : com.test.ClassToCopy@42e816 [varA=3], ClassToCopy : com.test.ClassToCopy@9304b1 [varA=4]]
[ClassToCopy : com.test.ClassToCopy@190d11 [varA=1], ClassToCopy : com.test.ClassToCopy@a90653 [varA=2], ClassToCopy : com.test.ClassToCopy@de6ced [varA=3], ClassToCopy : com.test.ClassToCopy@c17164 [varA=4]]

Upvotes: 2

Balakrishna
Balakrishna

Reputation: 166

Hi Floose try the following. It is working .

import java.util.Collections;
import java.util.Vector;

public class VectorCopyTest {

Vector<String> variables;

   void create_c(Vector l)
   {    
     Vector<String> variables = new Vector<String>();
     variables.setSize(l.size()); // so that variables has enough capacity to store l
     /*variables= l.clone();*/
     Collections.copy(variables, l);
     System.out.println(variables.size());
    }

   public static void main(String a[]){
       Vector<String> variables1 = new Vector<String>();
       variables1.addElement("hi");
       variables1.addElement("hello");
       VectorCopyTest copyTest = new VectorCopyTest();
       copyTest.create_c(variables1);
   }

}

Upvotes: 1

Related Questions