以下示例取自GenericsFAQ:
class Pair<X,Y> {
private X first;
private Y second;
public Pair(X a1, Y a2) {
first = a1;
second = a2;
}
public X getFirst() { return first; }
public Y getSecond() { return second; }
public void setFirst(X arg) { first = arg; }
public void setSecond(Y arg) { second = arg; }
}
问题:我想强制执行X
并且Y
应该是同一类型。示例Pair<Integer,Integer>
是正确的,但Pair<Integer, String>
不应被接受。是否有可能通过泛型实现这一目标?