Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 246
Richard Szalay Avatar asked Jan 04 '10 19:01

Richard Szalay


3 Answers

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.

like image 83
Jeremy Raymond Avatar answered Oct 09 '22 11:10

Jeremy Raymond


In .Net, "primitive" types are backed by objects. In Java, there's a hard distinction between primitive types and Objects. Java 5 introduced autoboxing, which can coerce between the two in certain situations. However, because the Java generics system uses type-erasure, there isn't enough information to autobox in this case.

like image 24
JohnE Avatar answered Oct 09 '22 11:10

JohnE


Java collections only allow references not primitives. You need to use the wrapper classes (in this case java.lang.Integer) to do what you are after:

private Dictionary<String, Integer> map;

they you can do things like:

int foo = map.get("hello");

and

map.put("world", 42);

and Java uses autoboxing/unboxing to deal with the details of the conversion for you.

Here is a little description on it.

like image 38
TofuBeer Avatar answered Oct 09 '22 12:10

TofuBeer