ClassCastException。怎么解决?

问题描述 投票:0回答:1

我想以有序的形式获取键,所以我使用了排序映射,但我得到了

ClassCastException
,因为我想知道我的程序中这个问题的原因,或者我做错了什么?

我的示例代码如下:

  public class TreeTest
{
    public static void main(String[] args)
    {
        SortedMap<SectorInfo, List<String>> map2 =
                new TreeMap<TreeTest.SectorInfo, List<String>>();
        ArrayList<String> list = new ArrayList<String>();
        ArrayList<String> list1 = new ArrayList<String>();
        ArrayList<String> list2 = new ArrayList<String>();

        list.add("Test1");
        list.add("Test2");
        list1.add("Test3");
        list1.add("Test4");
        list2.add("Test5");
        list2.add("Test6");
        map2.put(new SectorInfo("S1", "P1"), list);
        map2.put(new SectorInfo("S2", "P2"), list1);
        map2.put(new SectorInfo("S3", "P3"), list2);
    for (SectorInfo sectorInfo : map2.keySet())
        {
            System.out.println(SectorInfo.pName +" In " + SectorInfo.sName);
        }
    }

    protected static class SectorInfo
    {

        public String sName;
        public String pName;

        SectorInfo(String sName, String pName)
        {
            this.sName = sName;
            this.pName = pName;
        }
    }
}
java classcastexception
1个回答
6
投票

您的

SectorInfo
类未实现
Comparable
,并且您在创建
Comparator
时未提供
TreeMap
。因此出现错误。

因此,解决方案是修复上面这两点中的任何一个;)

编辑:

Comparator
的示例:

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);
© www.soinside.com 2019 - 2024. All rights reserved.