Java Associative Array (Sort Of)

Attached File(s): 

Ever wish that Java had associative arrays (aka assoc arrays) like in PHP?  As in, $x["name"] = "Bill" ?  Well, I created a helper class for Java which comes close to approximating it.  It can even loop through it similar to foreach().

ipad-java.jpgI call the class PseudoAssocArray, because it actually uses a HashMap to do the behind the scenes work. 

Simply include the file attached at the top of the page in your project, then use it like so:

PseudoAssocArray temp = new PseudoAssocArray(1);
temp.put("name", "April");
temp.put("age", "26");
// ...
String n = temp.get("name");

You can even make it be 2 dimensional by supplying a 2 in the constructor.  For example:

PseudoAssocArray temp = new PseudoAssocArray(2);
temp.put(0, "name", "April");
temp.put(1, "name", "Samuel");
// ...
String n = temp.get("1", "name");

Loop through like so:

temp.resetCounter(); //always do this first
while (temp.hasMore()) {
  Object obj = temp.getNext();
  // or: String s = (String) temp.getNext();
}

To loop through and get both key and value, try this:

temp.resetCounter();
while (temp.hasMore()) {
  Map<String, Object> entry = temp.getNextMap();
  String key = (String) entry.get("key");
  String value = (String) entry.get("value");
}

Enjoy!

 


Software License Fine Print

Creative Commons LicenseThis code is licensed as-is, with no warranty or guarantee, under a Creative Commons Attribution 3.0 Unported License.

You may use this code however you want, even in commercial products, but only if you include attribution to me, Richard Peacock, as the original author of this small portion of code, but not in a way that implies I endorse your project.

For example, on a Help/Credits screen:  Portions of this project were based on work freely obtained from these developers: Richard Peacock (http://richardpeacock.com), NAME HERE, etc.  These outside developers neither endorse nor support this software.

If you use this code, feel free to email me to let me know!  I'll include a link to your project here.