I would like to cast int count to an Integer count. I am using a Hashtable and here is the code... Hashtable quotes = new Hashtable(); int count=112;
String quote1="a test"; String quote2="a test again"; String quote3="a test num 3"; String quote4="a test num 4"; String quote6="a test last6"; String quote5="a test last"; String quote7="a test7"; String quote8="a 8"; String quote9="a999";
quotes.put("111", quote1); quotes.put(Integer(count), quote2); // why an error??? quotes.put("113", quote3); quotes.put("114", quote4); quotes.put("115", quote5); quotes.put("116", quote6); quotes.put("117", quote7); quotes.put("118", quote8); quotes.put("119", quote9); The java docs say that the put method can only have parameters of type Object. So when I try to cast an int to an Integer, it should work, but why doesn't it? Please explain.
It should also be mentioned that casting is done by surrounding the classname with brackets, so what you are doing is not casting, but making a new Integer object. Hopefully, obj is an object that can be successfully cast to an Integer.
When you take your items out of the Hashtable, you'll need to cast them back to Strings...
Mike, The cast exmaple that you have given below won't work with the given question. The count variable is of type int. Compiler would give an error message saying Invalid cast from int to Integer Integer i = (Integer) obj; //cast Integer i =(Integer)count; // Error -> Invalid cast from int to Integer
I believe I didn't try to cast an int to an Integer. Where do I have in my code Integer i = (Integer) count ?
I have Integer i = (Integer) obj. Then I continue to say that hopefully obj is an *object* that can be cast to an Integer (namely, an Integer object).
Perhaps I should have been more clear that my first code block was not in reference to the posted code sample at all, whereas my second code block did make use of some variable names previously posted. [This message has been edited by Mike Curwen (edited July 06, 2001).]