aryaxt
aryaxt

Reputation: 77596

Java - Getting rid of a compiler warning?

i have the following line of code which displays the following warning:

HashMap<String,String> currentItem = (HashMap<String,String>) adapter.getItemAtPosition(position);
// Warning: Type Safety: Unckecked cast from Object to HashMap <String,String>

How can i get rid of this warning?

Upvotes: 2

Views: 748

Answers (5)

Tom Seidel
Tom Seidel

Reputation: 9535

You can disable this warning in your compiler preferences, see picture..

enter image description here

Upvotes: 1

Mike Samuel
Mike Samuel

Reputation: 120516

If the getter is returning an Object because its generic, then you should verify that it does contain string values.

You can use a checked map to enforce the contract though:

Map<String, String> currentItem = Collections.checkedMap(
     adapter.itemAtPosition(position), String.class, String.class);

See http://download.oracle.com/javase/6/docs/api/java/util/Collections.html#checkedMap%28java.util.Map,%20java.lang.Class,%20java.lang.Class%29

Upvotes: 0

Adam Bryzak
Adam Bryzak

Reputation: 2668

You can suppress it with the @SuppressWarnings("unchecked") annotation on the line before the declaration:

@SuppressWarnings("unchecked")
HashMap<String,String> currentItem = (HashMap<String,String>) adapter.getItemAtPosition(position);
// Warning: Type Safety: Unckecked cast from Object to HashMap <String,String>

If you do this though, you should add a comment indicating why it's type-safe to cast it to a map of strings to strings.

Alternatively, if you're reading from the map only, you can cast it to HashMap<?, ?> and check the type of the objects you get out of the map with instanceof.

Upvotes: 3

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285405

Have the getItemAtPosition method return a generic HashMap, so you don't have to cast it. Either that or use the appropriate annotation -- @SuppressWarnings("unchecked")

Upvotes: 4

rkg
rkg

Reputation: 5719

You can use the SuppressWarnings annotation.

http://download.oracle.com/javase/1.5.0/docs/api/java/lang/SuppressWarnings.html

But I would discourage you to do that, if you have access to the adapter and can refactor it, take advantage of Java generics and return the correct type.

Upvotes: 1

Related Questions