//主PROGRAMM的我創建的書的對象,並將其插入到一般的鏈表,但即時通訊無法訪問鏈表中的類書的所有方法調用實際的類方法
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));
}
//想獲得實際的名稱和在這裏顯示列表方法的書auther名
/*
* 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");
}
}
您是否熟悉[PECS](https://stackoverflow.com/questions/2723397/what-is-pecs-producer-extends-consumer-super)成語?你的班級的通用性說「我可以處理任何事情」,但DisplayList方法說「我只能處理書籍」。哪一個必須主導? –
'AnyType'顧名思義可以代表任何類型,所以不保證它是Book。它可以是不帶'getData()'方法的類型。最簡單的解決方案是使用所有類型都具有'toString()'的方法。只需在您的'Book'類中覆蓋此方法並返回要打印的數據。 – Pshemo
非常感謝Pshemo,但有什麼方法可以調用鏈接列表中的每本書的方法 – striker