4

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

4 Answers 4

4

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.

Sign up to request clarification or add additional context in comments.

Comments

4

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

2 Comments

Thanks for the feedback. I didn't really need to use the TreeSet, however I agree I would have needed to implement comparable for if I used TreeSet. Using Hash set have given me the result I needed.
I am afraid I am new to posting question here. How can I mark the answer as answered?
0

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

Comments

0

Your Element must implement Comparable interface.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.