tags:

views:

62

answers:

3

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

+1  A: 

Sometimes, you as a programmer know that the warning is not a problem, however there is no way to convince the compiler simply by modifying code.. this is why it's a warning and not an error.

In these cases, you can add a SuppressWarnings annotation above your assignment:

@SuppressWarnings("unchecked")
Vector<Myobject> v2 = (Vector<Myobject>) v1.clone();
pstanton
+3  A: 

Try using the copy constructor instead:

Vector<Myobject> v2 = new Vector<Myobject>(v1);
harto
Well, it's not like there's anything wrong with _clone_ method :) (nothing I know about)
Nikita Rybak
clone can have unreliable results (depending on who wrote the implementation, and what approach they took) therefore it's better practice to avoid clone in many cases and in this case it's tidier too.
pstanton
+2  A: 

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.

oksayt