2017-02-12 78 views
1

我開始使用Java的泛型,似乎缺少一個關鍵組件。原始類型/ T無法解析

首先,我做了一些對原材料型閱讀需要的參數,實現沒有太多做的,因爲它們是通用的,但我的問題是BagInterfaceLinkedBag之間的相互作用:

package Chapter3; 

public interface BagInterface<T> { 

/** Gets the current number of entries in the bag. 
* @return the integer number of entries in the bag. */ 
public int getCurrentSize(); 

/** Sees whether this bag is full. 
*@return true if the bag is full, or false if not. */ 
public boolean isFull(); 

/** Sees whether the bag is empty. 
*@return true if bag is empty, or false if not. */ 
public boolean isEmpty(); 

/** Adds new entry to this bag. 
*@param newEntry the object to be added as a new entry 
*@return if the addition was successful, or false if not. */ 
public boolean add(T newEntry); 

/** Removes one unspecified entry from this bag, if possible. 
*@return either the removed entry, if the removal was successful, or null. */ 
public T remove(); 

/** Removes one occurrence of a given entry from this bag. 
*@param anEntry the entry to be removed 
*@return true id the removal was successful, or false if not. */ 
public boolean removal(T anEntry); 

/** Removes all entries from this bag. */ 
public void clear(); 

/** Counts the number of times a given entry appears in this bag. 
*@param anEntry the entry to be counted 
*@return the number of times anEntry appears in the bag. */ 
public int getFrequencyOf(T anEntry); 

/** Tests whether this bag contains a given entry. 
*@param anEntry the entry to locate 
*@return true if this bag contains anEntry, or false if not. */ 
public boolean contains(T anEntry); 

/**Retrieves all entries that are in this bag. 
*@return a newly allocated array of all the entries in the bag */ 
public T[] toArray(); 
} 

的兩個錯誤做有T沒有得到解決

package Chapter3; 

public class LinkedBag implements BagInterface { 

// reference to first node 
private Node firstNode; 
private int numberOfEntries; 

// default constructor 
public LinkedBag() { 

firstNode = null; 
numberOfEntries = 0; 
} 

// second constructor 
(error occurs here) public LinkedBag(T[] item, int numberOfItems) { 
this(); 
for(int index = 0; index < numberOfItems; index++) 
add(item[index]); 
}` 

另一個是是與get.data但我相信,也有以T沒有解決

(error occurs here) result[index] = currentNode.getData(); 
index++; 
currentNode = currentNode.getNextNode(); 
}// end while 
return result; 
}// end is full 

我已經轉錄完整的.java文件,注意是否需要更多信息,但我試圖保持它的特定和簡潔。

+0

你會得到什麼錯誤?你能分享他們的確切文字嗎?對T – Mureinik

+0

錯誤是 「T不能被解析爲一個類型」 在錯誤的getData() 「從類型LinkedBag.Node方法的getData()是指缺少類型T」 – DR4QU3

+0

什麼行會產生這個錯誤? – Mureinik

回答

2

LinkedBag在您分享的代碼中實現原始BagInterface。如果你想參考它的類型說明,你也應該添加類型參數到LinkedBag,並讓它以某種方式參考BagInterface類型。例如:

public class LinkedBag<T> implements BagInterface<T> { 
// Here --------------^---------------------------^ 
+0

謝謝我,昨晚正在這個工作,並打牆,我在工作,所以我無法測試它,但我會這樣做,看看我的問題解決了..我雖然也許我只是沒有將類連接在一起,但它們存在於同一個包中(再次我的編譯器知識也是有限的) 只在本學期開始使用eclipse – DR4QU3