Sorted Map中的ClassCastException.如何解决?

Sid*_*rth -1 java core classcastexception

我希望得到有序形式的键,所以我使用了Sorted Map,但我得到了"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;
      }
  }
}
Run Code Online (Sandbox Code Playgroud)

fge*_*fge 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);
Run Code Online (Sandbox Code Playgroud)