简体   繁体   English

不兼容的类型-SortedSet和TreeSet

[英]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> ). 在向地图添加元素时,您可以在地图中指定值的实际类型,同时必须使用声明属性时使用的相同类型(即StringSortedSet<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 ). 尽管SortedSetTreeSet实现相同的接口( 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 这个问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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