5

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?

Jim Jeffries
  • 9,841
  • 15
  • 62
  • 103

4 Answers4

7

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.

broc
  • 222
  • 1
  • 2
6

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>();
    }
Lawrence Dol
  • 63,018
  • 25
  • 139
  • 189
0

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();
}
lukastymo
  • 26,145
  • 14
  • 53
  • 66
-3

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>.

Piyush Mattoo
  • 15,454
  • 6
  • 47
  • 56