简体   繁体   中英

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?

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")

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 .

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.

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

在此输入图像描述

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM