Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/317.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 已排序映射中的ClassCastException。如何解决?_Java_Core_Classcastexception - Fatal编程技术网

Java 已排序映射中的ClassCastException。如何解决?

Java 已排序映射中的ClassCastException。如何解决?,java,core,classcastexception,Java,Core,Classcastexception,我想得到有序形式的键,所以我使用了排序映射,但我得到了“ClassCastException”,因为我想知道我的程序中出现这个问题的原因,或者我做错了什么。请推荐我。谢谢 我的示例代码如下: 公共类树测试 { 公共静态void main(字符串[]args) { 分类地图map2= 新树映射(); ArrayList=新建ArrayList(); ArrayList list1=新的ArrayList(); ArrayList list2=新的ArrayList(); 列表。添加(“测试1”);

我想得到有序形式的键,所以我使用了排序映射,但我得到了“ClassCastException”,因为我想知道我的程序中出现这个问题的原因,或者我做错了什么。请推荐我。谢谢 我的示例代码如下:

公共类树测试
{
公共静态void main(字符串[]args)
{
分类地图map2=
新树映射();
ArrayList=新建ArrayList();
ArrayList list1=新的ArrayList();
ArrayList list2=新的ArrayList();
列表。添加(“测试1”);
列表。添加(“测试2”);
清单1.添加(“测试3”);
清单1.添加(“测试4”);
清单2.添加(“测试5”);
清单2.添加(“测试6”);
地图2.put(新部门信息(“S1”、“P1”),列表);
map2.put(新的SectorInfo(“S2”、“P2”),列表1);
map2.put(新部门信息(“S3”、“P3”),列表2);
对于(SectorInfo SectorInfo:map2.keySet())
{
System.out.println(SectorInfo.pName+“In”+SectorInfo.sName);
}
}
受保护的静态类SectorInfo
{
公共字符串sName;
公共字符串pName;
SectorInfo(字符串sName、字符串pName)
{
this.sName=sName;
this.pName=pName;
}
}
}

您的
SectorInfo
类未实现
Comparable
,并且在创建
TreeMap
时,您没有提供
比较器。因此出现了错误

因此,解决方案是解决上述两点中的任一点;)

编辑:比较器的示例

private static final CMP = new Comparator<SectorInfo>()
{
    @Override
    public int compare(final SectorInfo a, final SectorInfo b)
    {
        final int cmp = a.sName.compareTo(b.sName);
        return cmp != 0 ? cmp : a.pName.compareTo(b.pName);
    }
}

// building the map:
final SortedMap<SectorInfo, List<String>> map2 
    = new TreeMap<SectorInfo, List<String>>(CMP);
private static final CMP=new Comparator()
{
@凌驾
公共整数比较(最终扇区信息a、最终扇区信息b)
{
最终整数cmp=a.sName.compareTo(b.sName);
返回cmp!=0?cmp:a.pName.compareTo(b.pName);
}
}
//构建地图:
最终分类地图map2
=新树形图(CMP);

哪一行导致了错误?@Smutje我在map2.put(新的SectorInfo(“S2”,“P2”),列表1)上得到了错误;仅供参考:行System.out.println(SectorInfo.pName+“In”+SectorInfo.sName);您应该有sectorInfo,因为您并没有静态字段pName,所以我想您应该显示实例的字段。
private static final CMP = new Comparator<SectorInfo>()
{
    @Override
    public int compare(final SectorInfo a, final SectorInfo b)
    {
        final int cmp = a.sName.compareTo(b.sName);
        return cmp != 0 ? cmp : a.pName.compareTo(b.pName);
    }
}

// building the map:
final SortedMap<SectorInfo, List<String>> map2 
    = new TreeMap<SectorInfo, List<String>>(CMP);