Java 树形图在SortedSet中的应用
为什么我们不能在SortedSet接口中使用其他类,如HashSet、HashMap或其他类来代替TreeMap/TreeSetJava 树形图在SortedSet中的应用,java,collections,sortedset,Java,Collections,Sortedset,为什么我们不能在SortedSet接口中使用其他类,如HashSet、HashMap或其他类来代替TreeMap/TreeSet import java.util.HashSet; import java.util.Iterator; import java.util.SortedSet; import java.util.TreeSet; public class SortedSetDemo { public static void main(String[] args)
import java.util.HashSet;
import java.util.Iterator;
import java.util.SortedSet;
import java.util.TreeSet;
public class SortedSetDemo
{
public static void main(String[] args)
{
SortedSet s=new HashSet();
s.add("Akash");
s.add("Prakash");
s.add("Bhushan");
s.add("Chetan");
System.out.println("SortedSet:");
Iterator itr=s.iterator();
while(itr.hasNext())
{
System.out.println(itr.next());
}
}
}
输出:
线程“main”java.lang中出现异常。错误:未解决的编译问题:
类型不匹配:无法从HashSet转换为SortedSet
at SortedSetDemo.main(SortedSetDemo.java:10)
您必须使用
Set
接口,而不是使用classSortedSet
。HashSet
不实现SortedSet
接口(HashSet未排序)。因此,您无法将哈希集
实例分配给SortedSet
变量。因为哈希集
不是SortedSet
在中,您找不到SortedSet。您无法使HashSet的对象引用SortedSet。因为HashSet的exteds AbstractSet未实现SortedSet。您可以使用Set接口替换SortedSet 设置-->抽象集-->哈希集-->链接哈希集和
设置-->排序集-->树集
SortedSet/SortedMap是对数据进行排序的接口,因此在对数据进行排序时,您可以直接使用TreeSet/TreeMap类,因为这些类直接实现SortedSet/SortedMap首先,不要尝试运行未编译的代码。其次,
HashSet
根本不是一个SortedSet
——你为什么希望它能工作?因为HashSet没有实现SortedSet接口。您可以选择用户树集或设置接口。若你们想知道为什么Hashset不在SortedSet的层次结构中,你们需要咨询那个些类的实现者。有什么特别的原因,你们想这样做吗??将hashset对象分配给sortedset接口变量???