HashTable Issue

hashtable, java, java-me, java1.4

Solution

In my answer I suppose that your actual code was in fact the following:

Hashtable table = new Hashtable();
table.put(1, "Hello World");

That's the code which causes the error you have described, i.e.

The method `put(Object, Object)` in the type `Hashtable` is not applicable for the arguments `(int, String)`

The reason is this:

Java 1.4 does not support generics, so the `Hashtable` simply works with `Objects` (both as keys as well as values)

Java 1.4 does not support autoboxing, so the code `table.put(1, "Hello World")` is not automatically autoboxed to `table.put(Integer.valueOf(1), "Hello World")`. Hence you are trying to call `table.put(int, String)` which is not compatible with `Hashtable.put(Object, Object)`.

Voila.

If you used Java 1.5+, the call would be autoboxed to `table.put(Integer, String)`

BTW, do not use `new Integer(1)`, always prefer the static factory method `Integer.valueOf(1)`. You may avoid unnecessary creation of redundant classes. This is what the autoboxing is compiled into. See this: Static factory methods vs Instance (normal) constructors?

Problem

I have an interesting question which entails the use of `Hashtables`; I'm developing for S40 Nokia's (with compliance level 1.4) How I expect the `Hashtable` to work: ``` Hashtable table = new Hashtable(); table.put(1, "Hello World"); ``` However I get the error: The method `put(Object, Object)` in the type `Hashtable` is not applicable for the arguments `(int, String)` However when I create an object reference and pass the reference, it works fine! Why?! Working example: ``` Hashtable table = new Hashtable(); Integer test = new Integer(1); table.put(test, "Hello World"); ``` Any explanations would be great!

Original source

Related problems