chimeracoder
chimeracoder

Reputation: 21682

Remove Compile-Time warnings about unchecked operations

The following line causes compile time warnings:

ArrayList<Integer> a = (ArrayList) b.clone();

creates:

Note: MyClass.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.

How do I remove the compile-time warnings? -Xlint:none and -nowarn do not seem to help.

Edit: I don't really care too much about being typesafe; in the context of the code, I'm sure that the types will work. I just want to suppress the compiler warnings.

Upvotes: 3

Views: 5669

Answers (3)

Paŭlo Ebermann
Paŭlo Ebermann

Reputation: 74750

You can use @SuppressWarnings("unchecked") before this variable declaration, this should help getting rid of the warning.

Unfortunately there is not really a way to do this cloning in a typesafe way, you have to trust the clone method to really only return integers in the new ArrayList.

If you don't want such compiler warnings in general, you can add -Xlint:-unchecked to turn off all warnings about unchecked generic conversions. Then the type safety from generics is quite gone, though.

Upvotes: 9

Puce
Puce

Reputation: 38132

Use:

List<Integer> a = new ArrayList<Integer>(b);

Upvotes: 5

user153498
user153498

Reputation:

It's because you're casting a generic ArrayList to a non-generic one. You have to cast it to a generic ArrayList:

ArrayList<Integer> a = (ArrayList<Integer>)b.clone();

Also, in the future, try compiling with -Xlint:unchecked, as the error message says.

Upvotes: 2

Related Questions