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开发者_如何学JAVA();
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
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.
Try using the copy constructor instead:
Vector<Myobject> v2 = new Vector<Myobject>(v1);
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();
精彩评论