Cannot get rid of Java warnings when cloning a 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 populate v1 with a bunch of Myobjects.

I need to make a shallow clone from v1 to v2. I tried:

v2 = v1.clone();

I get "unverified or unsafe operations."

I have tried all forms of casting and seem to be unable to overcome this warning.

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

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

or

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

... still getting it.

I am sure that I am missing something very elementary here ...

Thanks in advance

+3
source share
3 answers

(, Object, clone()) . , Vector<Myobject> , , . , .

. .

, v1, - .

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

, Myobject v1 v2.

+5

:

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

Sometimes, as a programmer, you know that warning is not a problem, but there is no way to convince the compiler simply by changing the code. This is why this is a warning, not an error.

In these cases, you can add an annotation SuppressWarningsabove your destination:

@SuppressWarnings("unchecked")
Vector<Myobject> v2 = (Vector<Myobject>) v1.clone();
+2
source

Source: https://habr.com/ru/post/1764796/


All Articles