简体   繁体   English

Java - 摆脱编译器警告?

[英]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. 让getItemAtPosition方法返回一个通用的HashMap,因此您不必强制转换它。 Either that or use the appropriate annotation -- @SuppressWarnings("unchecked") 或者使用适当的注释 - @SuppressWarnings(“unchecked”)

You can suppress it with the @SuppressWarnings("unchecked") annotation on the line before the declaration: 您可以在声明之前的行上使用@SuppressWarnings("unchecked")注释来禁止它:

@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 . 或者,如果您只是从地图中读取,则可以将其HashMap<?, ?>HashMap<?, ?>并使用instanceof检查从地图中获取的对象的类型。

You can use the SuppressWarnings annotation. 您可以使用SuppressWarnings注释。

http://download.oracle.com/javase/1.5.0/docs/api/java/lang/SuppressWarnings.html 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. 但我不鼓励你这样做,如果你有权访问adapter并可以重构它,利用Java泛型并返回正确的类型。

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. 如果getter返回一个Object因为它是泛型的,那么你应该验证它确实包含字符串值。

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 请参阅http://download.oracle.com/javase/6/docs/api/java/util/Collections.html#checkedMap%28java.util.Map,%20java.lang.Class,%20java.lang.Class%29

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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