Just attempting this question I found in a past exam paper so that I can prepare for an upcoming Java examination.
Provide a generic class Pair for representing pair
You can look to implementation of standard Java classes AbstractMap.SimpleEntry and AbstractMap.SimpleImmutableEntry. It is pretty easy to google sources:
I think No. Quote:
"the class should be parameterised over two types..."
I think they are expecting in terms of :
public class Pair<ThingA, ThingB>
Getters are broken
public thing getFirst() {
return thing.first;
}
public thing getSecond() {
return thing.second;
}
thing
should be replaced with this
thing
is a Type Variable in an unsual notation - we usually use one uppercase latter (like T
). Then: a type variable does not have any methods, so your getters won't compile.
Quick improvement: replace all thing
with T
Quick fix for getters:
public T getFirst() {
return first;
}
public T getSecond() {
return second;
}
One requirement was to allow two different types for the pair members. So the class signature should look like:
public Pair<S,T> {
private S first;
private T second;
//...
}
I implemented something similar but with static builder and chained setters
public class Pair<R, L> {
private R left;
private L right;
public static <K,V> Pair<K, V> of(K k, V v) {
return new Pair<K,V>(k, v);
}
public Pair() {}
public Pair(R key, L value) {
this.left(key);
this.right(value);
}
public R left() {
return left;
}
public Pair<R, L> left(R key) {
this.left = key;
return this;
}
public L right() {
return right;
}
public Pair<R, L> right(L value) {
this.right = value;
return this;
}
}
Apache Commons Lang has a generic pair implementation
https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/tuple/Pair.html