Using keys in Java arrays?


DevX Home    Today's Headlines   Articles Archive   Tip Bank   Forums   

Results 1 to 2 of 2

Thread: Using keys in Java arrays?

  1. #1
    Join Date
    Oct 2004
    Posts
    13

    Using keys in Java arrays?

    A PHP example:
    PHP Code:
    $arr = array("foo" => "bar"12 => true);

    echo 
    $arr["foo"]; // bar
    echo $arr[12];    // 1 
    $arr["foo"] = "bar"
    $arr[12] = 1

    Can you do this with Java arrays? If so, how?

  2. #2
    Join Date
    Sep 2004
    Posts
    150
    Yeah it's called a HashMap/Hashtable.

    The two are similar but Hashtable is safer for multiple threads. Other than that it doesn't matter which you use.


    Your PHP program is actually implementing a hash map/table but it is hiding that fact from you. All you see is the good stuff, the input and output.

    In Java it can be done but you must make a Hashtable and use its methods.

    Hashtable myTable = new Hashtable();

    myTable.put("foo", "bar");

    // myTable.get("foo") would return the "bar" string

    It's not implemented like an array though, as the items are not placed in any particular order. Regardless, they are returned in constant time (the best possible). It can be dumped into an array if needed, also.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center
 
 
FAQ
Latest Articles
Java
.NET
XML
Database
Enterprise
Questions? Contact us.
C++
Web Development
Wireless
Latest Tips
Open Source


   Development Centers

   -- Android Development Center
   -- Cloud Development Project Center
   -- HTML5 Development Center
   -- Windows Mobile Development Center