简体   繁体   中英

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>>();
    }
}

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>());

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 ).

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM