Suppose the getValues method returns a Map<String, String> :
private static Map<String, String> getValues() { HashMap<String, String> map = new HashMap<>(); map.put("abc", "def"); return map; }
If it is incorrect to work with it (using raw-type instead of generics), then such a situation is quite possible:
public static void main(String[] args) { HashMap<Integer, String> ranksList = (HashMap)getValues(); for (int i : ranksList.keySet()) { System.out.println("Key: " + i); } }
Which will lead to
java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer
Since, in fact, String participate in the hash table as keys, and you cannot make an Integer from String using a simple type conversion.
If the code were:
HashMap<Integer, String> ranksList = (HashMap<Integer, String>)getValues();
That would be a compilation error:
java.lang.RuntimeException: Uncompilable source code - incompatible types: java.util.Map<java.lang.String,java.lang.String> cannot be converted to java.util.HashMap<java.lang.Integer,java.lang.String>
It can be assumed that the getValues method returns just a Map , which is why
HashMap<Integer, String> ranksList = (HashMap<Integer, String>)getValues();
will not save the situation (the code will be compiled, but ClassCastException , of course, will not go anywhere), but this will be the fault of the developers of the getValues method.
And judging by the new screenshot

The getValues method returns a Map<String, Object> , which contains String as keys and which should not be attempted to be cast to Map<Integer, String> , because neither the type of keys does not match, nor the type of values.
If you cannot change the type returned by getValues , you can create a Map<Integer, String> based on Map<String, Object> :
HashMap<Integer, String> ranksList = new HashMap<>(); Map<String, Object> map = getValues(); for (String key : map.keySet()) { ranksList.put(Integer.parseInt(key), String.valueOf(map.get(key))); }
Or using Java 8:
HashMap<Integer, String> ranksList = new HashMap<>(); Map<String, Object> map = getValues(); map.forEach((key, value) -> ranksList.put(Integer.parseInt(key), String.valueOf(value)));
Also, do not forget that if any of the keys in the map does not fit the format adopted by the Integer.parseInt method, a Integer.parseInt will be NumberFormatException .