我是java新手,所以我不知道這個技術叫什麼,我可能在解釋事情上很窮,但我知道你明白。使用已確定的默認成員類型擴展ArrayList
假設我有此兩類,項目和它可能會擴展到ExtendedItem
public class Item { }
public class ExtendedItem extends Item {}
我想爲它創建集合包裝,所以我創建的ArrayList擴展一個類...(方案1)
public class DataSet extends ArrayList<Item> {}
然後現在初始化
DataSet dataset1 = new DataSet();
DataSet<ExtendedItem> dataset2 = new DataSet<ExtendedItem >();
dataset1.get(0) // yield Item instance... which is in this case, correct
dataset2.get(0) // also yield Item instance
,當我與克定義數據集eneric型...(方案2)
public class DataSet<T extends Item> extends ArrayList<Item> {}
它產生
DataSet dataset1 = new DataSet();
DataSet<ExtendedItem> dataset2 = new DataSet<ExtendedItem >();
dataset1.get(0) // yield Object instance.... dont't want this
dataset2.get(0) // yield ExtendedItem instance... correct
有什麼辦法(場景),所以這兩個數據集的產量正確的類型以「項目」爲默認類型?像這個:
DataSet dataset1 = new DataSet();
DataSet<ExtendedItem> dataset2 = new DataSet<ExtendedItem >();
dataset1.get(0) // yield Item instance
dataset2.get(0) // yield ExtendedItem instance
---------------------------編輯------------ ---------------
我可能找到了解決辦法:
public class DataSet<E extends Item> extends ArrayList<E> implements List<E>, RandomAccess, Cloneable, Serializable {
@Override
public E get(int i) {
return super.get(i);
}
@Override
public int size() {
return super.size();
}
}
與:
DataSet dataset1 = new DataSet();
DataSet<ExtendedItem> dataset2 = new DataSet<ExtendedItem >();
dataset1.get(0) // yield Item instance... correct
dataset2.get(0) // yield ExtendedItem instance... correct
可能的重複http://stackoverflow.com/questions/6101568/java-how-to-set-a-default-for-t-in-someclasst –