2010-05-06 96 views
2

对于一个类的任务,我们不能使用任何语言bultin类型,所以我坚持我自己的列表。总之,这里的情况:Java如何不接受通用中的LinkedList,但接受它自己的?

public class CrazyStructure <T extends Comparable<? super T>> { 
    MyLinkedList<MyTree<T>> trees; //error: type parameter MyTree is not within its bound 
} 

但是:

public class CrazyStructure <T extends Comparable<? super T>> { 
    LinkedList<MyTree<T>> trees; 
} 

作品。 MyTree实现了Comparable接口,但MyLinkedList没有。但是,根据this,Java的LinkedList也没有实现它。那么问题是怎么解决的?

MyLinkedList:

public class MyLinkedList<T extends Comparable<? super T>> { 
    private class Node<T> { 
     private Node<T> next; 
     private T data; 

     protected Node(); 
     protected Node(final T value); 
    } 

    Node<T> firstNode; 

    public MyLinkedList(); 
    public MyLinkedList(T value); 

    //calls node1.value.compareTo(node2.value) 
    private int compareElements(final Node<T> node1, final Node<T> node2); 

    public void insert(T value); 
    public void remove(T value); 
} 

MyTree:

public class LeftistTree<T extends Comparable<? super T>> 
     implements Comparable { 

    private class Node<T> { 
     private Node<T> left, right; 
     private T data; 
     private int dist; 

     protected Node(); 
     protected Node(final T value); 
    } 

    private Node<T> root; 

    public LeftistTree(); 
    public LeftistTree(final T value); 
    public Node getRoot(); 

    //calls node1.value.compareTo(node2.value) 
    private int compareElements(final Node node1, final Node node2); 

    private Node<T> merge(Node node1, Node node2); 
    public void insert(final T value); 
    public T extractMin(); 
    public int compareTo(final Object param); 
} 
+0

我们可以看到你的MyLinkedList定义吗? – OscarRyz 2010-05-06 22:02:31

+6

更好地向我们展示MyLinkedList和MyTree的声明。 – bmargulies 2010-05-06 22:03:00

+0

编辑方法签名,我可以发布其余的,如果你想 – 2010-05-06 22:32:02

回答

5

我假设你MyTree相同LeftistTree。签名的问题是它没有实现Comparable<LeftistTree<? super T>>

所以它的签名应该是:

public class LeftistTree<T extends Comparable<? super T>> 
    implements Comparable<LeftistTree<? super T>> 

的原因是你的MyLinkedList不像一个普通的LinkedList。一个普通的LinkedList的类型为:LinkedList<T> T上没有边界。你需要使用MyLinkedList参数实现它自己(或其超类)的Comparable,但实际上LeftistTree正在实现一个原始的Comparable(或Comparable<?>),所以Comparable是不保证与类型有关。

0

为什么您的链接列表必须接受输入Comparable

对于一个集合数据结构,强制你的集合只接受特定的数据类型是非常有限的。 如果您想要分类链接列表,最好接受任何元素并允许链接列表接受Comparator对象。如果你没有提供Comparator,那么你可以依靠包含元素的自然排序,如果它们是Comparable类型。

看一看SortedSetSortedMap api签名的一些例子。