假设我有一个如下类:

private class ComparableElement extends Element implements Comparable<ComparableElement> {

        @Override
        public int compareTo(ComparableElement o) {
            return getName().compareTo(o.getName());
        }
    }


其中元素定义如下:

public class Element {

    protected String name;

    protected String category;

    public Element() {
        super();
    }

    public Element(String _name, String _category) {
        super();
        this.name = _name;
        this.category = _category;
    }

    public String getName() {
        return name;
    }
}


然后,如果我有一个Element对象,将那个Element对象转换为ComparableElement实例的最佳实践是什么?就像是 :

Element e;
...
ComparableElement ce = (ComparableElement)e;


只是这不会工作...

最佳答案

您可以创建新的承包商ComparableElement

public ComparableElement (Element element )
{

     //Here you get all the data from the element and set it to this object.

}

10-08 01:55