我有一個泛型類應該創建一個數組中存儲的可比較集合。可比公司和仿製藥的工作方式我很不清楚。添加到泛型集合
public class OrderedCollection<T extends Comparable<? super T>>
{
private T collection[]; // the collection
private int size, tempValue; // how many elements currently stored
/**
* Constructor allocates array and initializes size
* @param size the number of elements stored
*/
public OrderedCollection (int capacity)
{
collection = (T[]) new Comparable[capacity];
size = 0;
}
}
首先,什麼樣的集合是收集(排列,列表等)。它永遠不會顯式實例化爲新的Array [],所以我很好奇它應該如何創建一個數組。其次,需要一種插入指定值(用於測試目的,我已經使用'5')並將其分配給集合[0]的方法。但是,當我返回集合[0]時,它返回爲空。這裏是插入方法:
public void insert(T x)
{
collection[0] = x;
}
沒什麼特別的。我將非常感謝一些澄清,爲什麼收集返回null,以及我應該如何去增加指定x價值的集合。
你可以看看[ArrayList的代碼](http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/7-b147/java/util/例如ArrayList.java#ArrayList。%3Cinit%3E%28int%29) - 等價構造函數確實:'collection = new Object [capacity];'。通用部分在其他方法中。例如:'public T get(int index)' – assylias