Java unchecked conversion

2019-01-20 13:31发布

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?

5条回答
来,给爷笑一个
2楼-- · 2019-01-20 13:46

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 of getSpecialCharMap() to HashMap<String, String>.

查看更多
老娘就宠你
3楼-- · 2019-01-20 13:49

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.

查看更多
时光不老,我们不散
4楼-- · 2019-01-20 13:51

Preceed the line with:

@SuppressWarnings("unchecked")

This will turn off the compiler warning.

查看更多
一纸荒年 Trace。
5楼-- · 2019-01-20 14:04

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:

private HashMap<String,String> getSpecialCharMap() {
    return new HashMap<String,String>();
    }
查看更多
Lonely孤独者°
6楼-- · 2019-01-20 14:11

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:

private static HashMap getSpecialCharMap() {
    return new HashMap();
}

public static void main(String[] args) {        
    HashMap<String,String> numberMap = getSpecialCharMap(); //warning
}

Example without warning:

...
@SuppressWarnings("unchecked")
public static void main(String[] args) {
    @SuppressWarnings("unused")
    HashMap<String,String> numberMap = getSpecialCharMap();
}
查看更多
登录 后发表回答