0

I'm trying to write a generic class for training.

public class Pair<T> {
    T first;
    T second;
    private Pair(T first, T second){
        this.first=first;
        this.second=second;
    }
    public T getFirst(){
        return first;
    }
    public T getSecond(){
        return second;
    }
}

And I made the ide add equals and hash itself.As a result, she wrote this implementation:

@Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Pair<?> pair = (Pair<?>) o;
        return Objects.equals(first, pair.first) && Objects.equals(second, pair.second);
    }

    @Override
    public int hashCode() {
        return Objects.hash(first, second);
    }

Since I haven't figured it out much yet, I don't understand this line:

Pair<?> pair = (Pair<?>) o;

Why <?> ? What kind of person will she put there and where will she take it from? I understand that Pair<T> pair = (Pair<T>) o; wrong, because there will be an erasure of the type , but what does<? >give us? I will be glad to help you figure it out, thank you.

Alpharius
  • 489
  • 5
  • 12
  • `Objects.equals(...)` don't care about the object type, it just compares two instances of type `Object`. As such, it doesn't matter what type `first` and `second` is, they're going to be implicitly cast to `Object` anyway, so `Pair>` is simply acknowledging that fact, leaving it up to the `equals(...)` methods of the objects to verify matching types. – Andreas Jul 04 '21 at 21:54

1 Answers1

0

Pair<?> is a syntactic sugar for Pair<? extends Object> it mean that your eaquls method will accept an object or a class extends object.

You can check this subject for more details Generics what does <?> actually mean?

  • And if you make a Pair, then > will it be String or Object? – Alpharius Jul 04 '21 at 22:04
  • @Alpharius: Neither. It's a `?`, which means that the code _doesn't know._ – Louis Wasserman Jul 04 '21 at 22:05
  • @Alpharius, declaring public class Pair {} make no sense it will be always a generic param like T as if you write class Pair {} – Maroine Mlis Jul 04 '21 at 22:10
  • @MaroineMlis it was the substitution of string instead of T that was interesting to me, if I understood you correctly – Alpharius Jul 04 '21 at 22:13
  • If you have Pair p1 = new Pair("A","B"); Pair p2 = new Pair("C","D"); and try to call p1.equals(p2) the equals method at the run time level will not change for this line Pair> pair = (Pair>) o; but the 'first' and 'second' attirbutes will be String fields – Maroine Mlis Jul 04 '21 at 22:20