Possible Duplicate:
Storing primitive values in a Java collection?
In java when I use the following :-
public HashMap<char, int> buildMap(String letters)
{
HashMap<char, int> checkSum = new HashMap<char, int>();
for ( int i = 0; i < letters.length(); ++i )
{
checkSum.put(letters.charAt(i), primes[i]);
}
return checkSum;
}
I get errors related to inappropriate types. I solved my problem by using Character and Integer instead of char and int respectively. However, I’m having trouble figuring out why HashMap fails to be able to deal with primitive data types.
Generic parameters can only bind to reference types, not primitive types, so you need to use the corresponding wrapper types. Try
HashMap<Character, Integer>instead.This is due to type erasure. Java didn’t have generics from the beginning so a
HashMap<Character, Integer>is really aHashMap<Object, Object>. The compiler does a bunch of additional checks and implicit casts to make sure you don’t put the wrong type of value in or get the wrong type out, but at runtime there is only oneHashMapclass and it stores objects.Other languages “specialize” types so in C++, a
vector<bool>is very different from avector<my_class>internally and they share no commonvector<?>super-type. Java defines things though so that aList<T>is aListregardless of whatTis for backwards compatibility with pre-generic code. This backwards-compatibility requirement that there has to be a single implementation class for all parameterizations of a generic type prevents the kind of template specialization which would allow generic parameters to bind to primitives.