简体   繁体   中英

'java.lang.ClassCastException: Resource cannot be cast to java.lang.Comparable'

I have a connector which has two ports. Two ports have a common root as Resource . I am trying to find that common root for those two ports.

I need a set of elements for one port(p1) which can be found via getParent method. For the other port (p2) I need to check if any of p2's element does exist in the set. Although I need this method to return an object of type Resource , I am bit stuck at this point. I am getting the following error.

Unexpected problem while loading: 'java.lang.ClassCastException: policy.vddl.model.Resource cannot be cast to java.lang.Comparable' java.lang.ClassCastException: vddl.model.Resource cannot be cast to java.lang.Comparable at java.util.TreeMap.compare(Unknown Source) at java.util.TreeMap.put(Unknown Source) at java.util.TreeSet.add(Unknown Source) at vddl.product.Product.findCommonRoot(Product.java:357)

private Element findCommonRoot(Connector connector)
{

    List<Port> portList = getListOfPort(connector);
    Port p1 = portList.get(0);
    Set<Element> portElementSet = new TreeSet<Element>();

    Element pathElement = p1.getParent();
    while (pathElement != null)
    {
        portElementSet.add(pathElement);
        pathElement = pathElement.getParent();
    }

    Port p2 = portList.get(1);
    Element pathElement2 = p2.getParent();

    for(Element e: portElementSet)
    {
        if(portElementSet.contains(pathElement2))
            pathElement2 = e;
    }

    return pathElement2;
}

TreeSet sorts the Comparable elements, So You need to make sure your Element implements Comparable

If you don't have access to source code of Element you can pass an instance of Comparator in the constructor of TreeSet

Use HashSet instead TreeSet if don't need the elements to be sorted. HashSet is not sorted and doesn't need the elements to be comparable.

TreeSet is a sorted set. any object you add to TreeSet should implement Comparable interface. See Java docs for add method on treeset

您的Element必须实现Comparable接口。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM