Java 未经检查的转换
我有以下代码行
this.htmlSpecialChars = this.getSpecialCharMap();
,
private HashMap<String,String> htmlSpecialChars;
但收到有关未经检查的转换的警告。我该如何停止这个警告?
I have the following line of code
this.htmlSpecialChars = this.getSpecialCharMap();
where
private HashMap<String,String> htmlSpecialChars;
but I get a warning about an unchecked conversion. How do I stop this warning?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
你得到这个是因为 getSpecialCharMap() 返回一个对象,其类型无法被编译器验证为 HashMap<字符串,字符串>。继续提供 getSpecialCharMap 的原型。
You're getting this because getSpecialCharMap() is returning an object whose type cannot be verified by the compiler to be HashMap< String, String>. Go ahead and provide the prototype for getSpecialCharMap.
您收到警告是因为编译器无法验证对,因为方法 getSpecialChars() 返回的是普通的非泛型 HashMap。
htmlSpecialChars
的赋值是否为 HashMap您应该修改您的方法以返回特定的泛型类型:
You are getting the warning because the compiler cannot verify that the assignment to
htmlSpecialChars
is a HashMap<String,String>, since the method getSpecialChars() is returning a plain, non-generic HashMap.You should modify your method to return the specific generic type:
最好的方法是将方法的返回类型修改为 numberMap 的类型或这种方式 - 请注意,这是非常糟糕的做法。不要告诉任何人我向您展示了这个:
带有未经检查的转换警告的示例:
没有警告的示例:
The best way will be to modify return-type of your method to numberMap's type or this way - please notice this is really bad practice. Don't tell anybody that I showed you this:
Example with unchecked conversion warning:
Example without warning:
getSpecialCharMap()
的返回类型是非泛型HashMap吗?未经检查的转换警告通常是由于泛型中的类型擦除而发生的。为了解决这个问题,您需要使用@SuppressWarnings("unchecked")
对该方法进行注释,或者将getSpecialCharMap()
的返回类型更改为HashMap<字符串,字符串>
。Is the return type of
getSpecialCharMap()
non-generic HashMap? Unchecked conversion warning typically happens because of Type Erasure in Generics. In order to get around this, you need to annonate the method with@SuppressWarnings("unchecked")
or change the return type ofgetSpecialCharMap()
toHashMap<String, String>
.