Skip to content

Instantly share code, notes, and snippets.

@mwanji
Created February 28, 2009 02:36
Show Gist options
  • Save mwanji/71838 to your computer and use it in GitHub Desktop.
Save mwanji/71838 to your computer and use it in GitHub Desktop.
// Pair and SmartMap in action
// Problems:
// 1. this gives a compiler warning: "Type safety : A generic array of Pair<String,String> is created for a
// varargs parameter"
// 2. All second elements of Pairs must be of same type, not even subclasses for it to compile.
public class Example {
public static void main(String[] args) {
SmartMap<String, String> myMap = map(of("key", "value1"), of("key2", "value 1"));
System.out.println(myMap.get("key"));
}
}
// Immutable tuple-ish thing
public class Pair<T, U> {
private final T first;
private final U second;
// factory method
public static <T, U> Pair<T, U> of(T first, U second) {
return new Pair<T, U>(first, second);
}
public T first() {
return first;
}
public U second() {
return second;
}
private Pair(T first, U second) {
this.first = first;
this.second = second;
}
// equals() and hashcode() omitted
}
// Map that takes Pairs and unpacks them to traditional key/value
public class SmartMap<K, V> extends HashMap<K, V> {
// factory method
public static <K, V> SmartMap<K, V> map(Pair<K, V>... pairs) {
return new SmartMap<K, V>().add(pairs);
}
public SmartMap<K, V> add(Pair<K, V>... pairs) {
for (Pair<K, V> pair : pairs) {
put(pair.first(), pair.second());
}
return this;
}
private SmartMap() { }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment