I want a data structure that allows me to map keys to values, like PHP's associative arrays. Each key can only exist once, but a value can be mapped to any number of keys. What am I looking for? Something in the Google Commons Collections?
You're looking for a HashMap, such as a HashMap<K,V>
. The former maps Objects to Objects, and the latter maps types of your choosing (like other generics).
The Map
structure is what you want. A good implementation is the HashMap
.
This data type does not allow the same value for the Key, but you can have as many duplicate values as you like.
Example usage:
Map<String, String> map = new HashMap<String, String>();
map.put("FirstName", "LastName");
System.out.println(map.get("FirstName")); // Prints 'LastName'
System.out.println(map.put("FirstName", "Foo")); // Prints 'LastName'
System.out.println(map.get("FirstName")); // Prints 'Foo'
In other words, the key can only exist once. Otherwise the value is overwritten.
What's wrong with regular HashMap? If your values are Strings you'll get reference counting for free and if you need to refer to a particular instance of object just don't allocate one, but use existing reference
HashMap is the way to go for sure. I actually view things the other way around when I first started coding in PHP. I was wondering, how do I implement a HashMap? Then I discovered associative arrays.