1

I have a (probably simple) question regarding genrics in Java. I have the following class:

public class ValueCollection<Y> implements Collection<Y>
{
    private Set<Entry<?, Y>> entries;

    public ValueCollection(Set<Entry<?, Y>> entries)
    {
        this.entries = entries;
    }
    ...
}

When I call the constructor like this:

return new ValueCollection<V>(entries);

I get the following compiler error:

The constructor ValueCollection<V>(Set<Map.Entry<K,V>>) is undefined

If I change my class to this:

public class ValueCollection<X, Y> implements Collection<Y>
{
    private Set<Entry<X, Y>> entries;

    public ValueCollection(Set<Entry<X, Y>> entries)
    {
        this.entries = entries;
    }
    ...
}

and my constructor call to this:

return new ValueCollection<K, V>(this.entries());

the compile error goes away. I'm just wondering why this is the case. Thanks for the help!

1
  • What if you just call the constructor with new ValueCollection<V>(entries) in the first case? Your first class only has one type parameter. Commented Jul 26, 2012 at 18:54

1 Answer 1

2

A Set<Entry<?, V>> is either a set of entries with any key type and value type V or a set of entries with some specific but unknown key type K and value type V. Due to the latter the compiler rejects your original constructor invocation.

A Set<? extends Entry<?, V>> is a set of entries which are entries with any key type and value type V. This is exactly what you want, redefine your constructor parameter type to be Set<? extends Entry<?, V>>.

You can assign the parameter to your field using either this.entries = Collections.unmodifiableSet(entries) or this.entries = new HashSet<Entry<?, V>>(entries). Both right hand sides produce a Set<Entry<?, V>> in a way that convinces the compiler it means a set of entries with any key type and value type V.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot! This is exactly what I wanted to know. Your explanation makes a lot of sense.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.