How to build a linked list which should store Elements of a given interface ( Sortable
)?
The interfaces to build on is:
public interface Sortable<T>
My implemementation of the list is called public class DoublyLinkedList
which stores data in nodes of the class public class DoublyLinkedListElement implements Sortable<Object>
So far so good. However there is another class public class Product implements Sortable<Product>
.
Is it possible to use Methods of DoublyLinkedList
to add objects of the type Product
to a DoublyLinkedList
without converting the type to DoublyLinkedListElement
. If I try so I receive actual argument Product cannot be converted to DoublyLinkedListElement by method invocation conversion .
I'm not positive I understand the problem but I think what you need to do is make your add method take type Sortable. Then you do not have to cast anything and you would be able to add Product or DoublyLinkedListElement.
DoubleLinkedList<Sortable> list = new DoublyLinkerList<Sortable>();
list.add(new Product());
list.add(new DoublyLinkedListElement());
I hesitate answering this question in full; but as generics are an acquired taste, maybe something like:
public class DoublyLinkedList<T extends Sortable<T>> {
private Element<T> first;
private Element<T> last;
}
class Element<T extends Sortable<T>> {
private T value;
private Element<T> previous;
private Element<T> next;
}
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.