I have a situation where I want to compare a List of Pairs in Java. I'll be using this Pair -interface from Apache.
A Pair's Left and Right value can be of a type that implements Comparable, so I declare the List as follows:
List<Pair<Comparable, Comparable>> listOfPairs;
The Left and Right value should always be of the same type, eg Pair<String, String>
or Pair<Integer, Integer>
, and both kinds of Pairs could be added to the same list.
This works:
Pair<Comparable, Comparable> p1 = new ImmutablePair<>("a", "b");
Pair<Comparable, Comparable> p2 = new ImmutablePair<>(2, 3);
listOfPairs.add(p1);
listOfPairs.add(p2);
This also works:
Pair<Comparable, Comparable> p3 = new ImmutablePair<>("a", 2);
listOfPairs.add(p3);
Is it possible to have a type check, to ensure that a Pair's types are of the same type, once it is added to the list, eg fail at compile time?
Yes, you can implement your own class that either extends ImmutablePair or the Pair class.
example:
public class MyPair<T> extends Pair<Comparable<T>, Comparable<T>> {
public MyPair(T key, T value) {
}
}
When you create an instance of such class, the generic T type will always be the same for both arguments.
Yes, if that variable is a local variable, then you can add a type parameter to the method where it's declared.
public <T extends Comparable> void myMethod() {
...
List<Pair<T, T>> listOfPairs;
...
If they're fields, you can add a type parameter to the class.
public class MyClass<T extends Comparable> {
...
private List<Pair<T, T>> listOfPairs;
...
Another alternative, if neither of these suits your situation, is to define your own Pair
generic class something like this with no members, then use it in place of Pair
as required. You'll need to write a constructor in this class, which just delegates to the superclass constructor
public class SelfPair<T> extends Pair<T,T> {
public SelfPair(T first, T second) {
super(first, second);
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.