[英]call actual class method from generic template type Object
//程序的主要部分,我创建了一个book对象,并将其插入到通用链接列表中,但是无法访问linklist类中book的所有方法
public static void main(String[] args) {
LinkedList<Book> list;
list = new LinkedList<>();
Book a=new Book();
a.setAuthur("ahsan");
a.setName("DSA");
a.setNoOfPages(12);
list.insertFirst(a);
}
//链接列表类
import java.util.NoSuchElementException;
public class LinkedList<AnyType> {
public class Node<AnyType>
{
private AnyType data;
private Node<AnyType> next;
public Node(AnyType data, Node<AnyType> next)
{
this.data = data;
this.next = next;
}
/**
* @return the data
*/
public AnyType getData() {
return data;
}
/**
* @param data the data to set
*/
public void setData(AnyType data) {
this.data = data;
}
/**
* @return the next
*/
public Node<AnyType> getNext() {
return next;
}
/**
* @param next the next to set
*/
public void setNext(Node<AnyType> next) {
this.next = next;
}
}
private Node<AnyType> head;
/*
* Constructs an empty list
*/
public LinkedList()
{
head = null;
}
public boolean isEmpty()
{
return head == null;
}
/*
* Inserts a new node at the beginning of this list.
* @param item to be inserted in First
*/
public void insertFirst(AnyType item)
{
head = new Node<AnyType>(item, head);
}
/*
* Returns the first element in the list.
* @return First element in linked List
*/
public AnyType getFirst()
{
if(head == null) throw new NoSuchElementException();
return head.getData();
}
/*
* Removes the first element in the list.
* @return Deleted First Item
*/
public AnyType deleteFirst()
{
AnyType tmp = getFirst();
head = head.getNext();
return tmp;
}
/*
* Recursively inserts a new node to the end of this list.
* @param item to be inserted in last
*/
public void insertLast(AnyType item)
{
if( head == null)
insertFirst(item);
else
insertLast(head, item);
}
private void insertLast(Node<AnyType> node, AnyType item)
{
if(node.getNext() != null) insertLast(node.getNext(), item);
else
node.setNext( new Node<AnyType>(item, null));
}
//想要在显示列表方法中在此处获取书籍的实际名称和作者姓名
/*
* Display all the elements in linked list
*/
public void DisplayList()
{
Node<AnyType> Current=head;
while(Current!=null)
{
System.out.print("[ "+ Current.getData()+" ] -> ");//want to print name of the book here
//i do the following but not worked Current.getData().getName();
Current=Current.getNext();
}
System.out.println("NULL");
}
}
简短的答案:您不能。
长答案:当您拥有Node<AnyType>
,我们所知道的就是该值是AnyType
某个实例。 它可能是Book
,也可能不是。 由于这是我们在编译时不知道的事情,因此我们不能允许调用Book
方法,而不能AnyType
。
如果您的要求是将书从清单中取出,则应将其设为Node<Book>
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.