Using int as a type parameter for java.util.Dictionary

Richard Szalay picture Richard Szalay · Jan 4, 2010 · Viewed 39.3k times · Source

When I try to declare a Dictionary as such:

private Dictionary<String, int> map;

The compiler gives me the following error:

Syntax error on token "int", Dimensions expected after this token

But it works fine with Integer. I'm vaguely aware that Java treats int / Integer differently (I come from a .NET background), but I was hoping someone could give me a full explanation on why I can't use primitives in a Dictionary<>

Answer

Jeremy Raymond picture Jeremy Raymond · Jan 4, 2010

In Java primitives aren't objects, so you can't use them in place of objects. However Java will automatically box/unbox primitives (aka autoboxing) into objects so you can do things like:

List<Integer> intList = new LinkedList<Integer>();
intList.add(1);
intList.add(new Integer(2));
...
Integer first = intList.get(0);
int second = intList.get(1);

But this is really just the compiler automatically converting types for you.