Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Map;
- import java.util.HashMap;
- public class CompositeMapsExample {
- public static void main(String[] args) {
- // Old and busted
- Map<String, Map<String, Object>> compositeMap = new HashMap<String, Map<String, Object>>();
- compositeMap.put("Jones", new HashMap<String, Object>());
- compositeMap.get("Jones").put("Jim", 5);
- System.out.println(compositeMap);
- // New hotness
- Map<Name, Object> compositeKey = new HashMap<Name, Object>();
- compositeKey.put(new Name("Jones", "Jim"), 5);
- System.out.println(compositeKey);
- }
- }
- class Name {
- public Name (String lastName, String firstName) {
- this.lastName = lastName;
- this.firstName = firstName;
- }
- public boolean equals(Object o) {
- if (o == null || o.getClass() != this.getClass())
- return false;
- return ((Name) o).lastName.equals(this.lastName) &&
- ((Name) o).firstName.equals(this.firstName);
- }
- public int hashCode() {
- return lastName.hashCode() + firstName.hashCode();
- }
- public String toString() {
- return lastName + ", " + firstName;
- }
- private final String lastName;
- private final String firstName;
- }
Add Comment
Please, Sign In to add comment