Snowcrash
Snowcrash

Reputation: 86247

Incompatible types - SortedSet and TreeSet

When I try to compile this:

import java.util.*;

public class NameIndex
{
    private SortedMap<String,SortedSet<Integer>> table;

    public NameIndex()
    {
        this.table = new TreeMap<String,TreeSet<Integer>>();
    }
}

I get:

Incompatible types - found java.util.TreeMap<java.lang.String,java.util.TreeSet<java.lang.Integer>> but expected java.util.String,java.util.SortedSet<java.lang.Integer>>

Any idea why?

UPDATE: This compiles:

public class NameIndex
{
    private SortedMap<String,TreeSet<Integer>> table;

    public NameIndex()
    {
        this.table = new TreeMap<String,TreeSet<Integer>>();
    }
}

Upvotes: 2

Views: 1826

Answers (3)

Vivin Paliath
Vivin Paliath

Reputation: 95558

Always type an object with the interface instead of the concrete type. So you should have:

private Map<String, Set<Integer>> table;

instead of what you have right now. The advantage is that you can switch out implementations whenever you want now.

Then:

this.table = new TreeMap<String, Set<Integer>>();

You get a compile-time error because SortedSet and TreeSet are different types, although they implement the same interface (Set).

Upvotes: 1

Xeon
Xeon

Reputation: 5989

You can always declare:

private SortedMap<String, ? extends SortedSet<Integer>> table;

but I suggest using:

private Map<String, ? extends Set<Integer>> table; // or without '? extends'

Look at this question

Upvotes: 1

&#211;scar L&#243;pez
&#211;scar L&#243;pez

Reputation: 236094

Try this:

this.table = new TreeMap<String, SortedSet<Integer>>();

You can specify the actual type of the values in the map when you add elements to it, meanwhile you must use the same types used at the time of declaring the attribute (namely String and SortedSet<Integer>).

For example, this will work when adding new key/value pairs to the map:

table.put("key", new TreeSet<Integer>());

Upvotes: 2

Related Questions