java不兼容类型SortedSet和TreeSet
当我试图编译此文件时:
import java.util.*;
public class NameIndex
{
private SortedMap<String,SortedSet<Integer>> table;
public NameIndex()
{
this.table = new TreeMap<String,TreeSet<Integer>>();
}
}
我得到:
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>>
知道为什么吗
更新: 这包括:
public class NameIndex
{
private SortedMap<String,TreeSet<Integer>> table;
public NameIndex()
{
this.table = new TreeMap<String,TreeSet<Integer>>();
}
}
# 1 楼答案
始终使用接口而不是具体类型键入对象。因此,你应该:
而不是你现在拥有的。其优点是,您现在可以随时切换实现
然后:
出现编译时错误是因为
SortedSet
和TreeSet
是不同的类型,尽管它们实现了相同的接口(Set
)# 2 楼答案
试试这个:
在向映射中添加元素时,可以指定映射中值的实际类型,同时必须使用声明属性时使用的相同类型(即
String
和SortedSet<Integer>
)例如,将新的键/值对添加到映射时,这将起作用:
# 3 楼答案
您可以随时声明:
但我建议使用:
请看this问题