Search code examples
javavectorclone

Can't shed Java warnings when cloning vector


I have two vectors declared as a private class property:

private Vector<Myobject> v1 = new Vector<Myobject>();
private Vector<Myobject> v2 = new Vector<Myobject>();

I fill up v1 with a bunch of Myobjects.

I need to do a shallow clone of v1 to v2. I tried:

v2 = v1.clone();

I get "unchecked or unsafe operations".

I've tried all forms of casting and cannot seem to overcome this warning.

Even if I remove the second (v2) declaration and try and just clone:

Vector<Myobject> v2 = v1.clone();

or

Vector<Myobject> v2 = ( Vector<Myobject> ) v1.clone();

... still get it.

I'm sure I'm missing something very basic here...

Thanks in advance


Solution

  • The compiler will always give a warning when casting a non-parametrized type (such as the Object returned by clone()) into a parametrized one. This is because the target type Vector<Myobject> is making guarantees about not only itself, but also objects contained within it. However there's no way to verify those guarantees at runtime because the type parameter information is erased.

    See here for a a more detailed explanation.

    As mentioned earlier, if you're just trying to make a copy of the vector v1, the proper way to do that is to use the copy constructor.

    Vector<Myobject> v2 = new Vector<Myobject>(v1);
    

    The resulting clone will be shallow as this only copies the Myobject references from v1 to v2.