Mahendran
Mahendran

Reputation: 2243

Enforcing same generics type in a class using generics

The following example is taken from 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; }
}

Question: I wanted to enforce X and Y should be of same type. Example Pair<Integer,Integer> is correct but Pair<Integer, String> should not be accepted. Is it possible to achieve this through Generics?

Upvotes: 0

Views: 82

Answers (2)

Paul
Paul

Reputation: 3058

Did you consider something like this?

class LikePair<Z> extends Pair<Z,Z> {

    public LikePair(Z a, Z b) {
        super(a, b);
    }

}

That way you get to keep the (potentially very useful) Pair class whilst also enforcing your 'likeness' constraint were needed.

As a matter of programming style I'd make Pair (and LikePair) immutable (final fields, no setters). Would also be good to implement equals(), hashCode(), toString(), etc.

Upvotes: 0

johnchen902
johnchen902

Reputation: 9609

Use

class Pair<X> {

And change all Y to X.

Upvotes: 11

Related Questions