开发者

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开发者_JS百科 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..

Java - Getting rid of a compiler warning?


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜