Results 1 to 2 of 2
  1. #1
    new_1 is offline Member
    Join Date
    Dec 2007
    Posts
    5
    Rep Power
    0

    Default Hashtable-put method

    Hi,
    I wrote a code, below is a part of it(using NetBeans IDE 6.0)
    Java Code:
    .............
    Hashtable<String, Integer> numbers= new Hashtable<String, Integer>();
       numbers.put("one", 1);
       numbers.put("two", 2);
       numbers.put("three", 3);
    ............
    Problem is the following:
    -in tutorials i read put() method just puts the parameter in the table(we didnt have to write n=numbers.put("one", Integer(1)) ).
    -when i wrote the above code, there was an error telling me that put() method returns an Integer.
    Help me understand please.
    Thanks.
    Last edited by new_1; 12-23-2007 at 12:21 PM.

  2. #2
    hardwired's Avatar
    hardwired is offline Senior Member
    Join Date
    Jul 2007
    Posts
    1,576
    Rep Power
    9

    Default

    The lines/snippet you posted compile(s) and run(s) okay.
    You mentioned an error for the return value of the put method. If I modify your code to explore this
    Java Code:
    Hashtable<String, Integer> numbers= new Hashtable<String, Integer>();
    numbers.put("one", 1);
    int m = numbers.put("two", 2);        // runtime error
    Integer n = numbers.put("three", 3);  // okay
    the line with "int m = ..." (line 7) throws a NullPointerException:
    Java Code:
    C:\jexp>java Test
    Exception in thread "main" java.lang.NullPointerException
            at Test.main(test.java:7)
    j2se 1.5+ has autoboxing which can cause trouble. The put method takes Objects for both key and value. Your Hashtable declaration specifies String(key) and Integer(value) which, according to the javadoc for the class api, will then return an Integer. So if you want a return value from the put method you will need an Integer (vis–a–vis an int primitive data type) to receive it (as shown above).

Similar Threads

  1. HashTable vs HashMap
    By bugger in forum New To Java
    Replies: 7
    Last Post: 01-06-2011, 03:15 PM
  2. Working with Key-Value Pairs in a Hashtable
    By Java Tip in forum java.lang
    Replies: 0
    Last Post: 04-12-2008, 08:44 PM
  3. Hashtable example
    By Java Tip in forum Java Tip
    Replies: 0
    Last Post: 02-15-2008, 08:43 AM
  4. HashTable problem
    By jhetfield18 in forum New To Java
    Replies: 2
    Last Post: 12-16-2007, 10:27 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •