有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

共 (3) 个答案

  1. # 1 楼答案

    始终使用接口而不是具体类型键入对象。因此,你应该:

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

    而不是你现在拥有的。其优点是,您现在可以随时切换实现

    然后:

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

    出现编译时错误是因为SortedSetTreeSet是不同的类型,尽管它们实现了相同的接口(Set

  2. # 2 楼答案

    试试这个:

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

    在向映射中添加元素时,可以指定映射中值的实际类型,同时必须使用声明属性时使用的相同类型(即StringSortedSet<Integer>

    例如,将新的键/值对添加到映射时,这将起作用:

    table.put("key", new TreeSet<Integer>());
    
  3. # 3 楼答案

    您可以随时声明:

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

    但我建议使用:

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

    请看this问题