Question

I'm writing a generic Pair class, that holds any two objects, (same or different types). I am writing now a copy constructor, however, I'm getting some errors which I'm not able to solve. My code is below:

public class Pair<T1, T2> {
    // Instance Fields
    private T1 first;
    private T2 second;

    // Constructors
    public Pair() {}

    public Pair(Pair<?, ?> p) {
        first  = p.first;  // error here
        second = p.second; // error here
    }
}

Is there a way for me to check for the types of the ? in the pair object using instanceof? If I cast p.first to T1 it works, but I want to make my class to be thorough and to handle any situation it might face, like if the user entered wrong object pair types, or other issues that might occur.

Another question is, is there a guideline or some kind of rules for using generics in Java?

Was it helpful?

Solution

Try ? extends T1 and ? extends T2 - this will ensure that your objects are of the same type or a subtype.

public class Pair<T1, T2> {
    // Instance Fields
    private T1 first;
    private T2 second;

    // Constructors
    public Pair() {}

    public Pair(Pair<? extends T1, ? extends T2> p) {
        first  = p.first;
        second = p.second;
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top