Re: [問題] 泛型類別...
※ 引述《csihcs (非天夜翔)》之銘言:
: 另外我想借標題問如何在 template 中,new 出實體?
: class Test {
: TemplateClass<String> ts = new TemplateClass<String>;
: String s = ts.newInstance();
: }
: class TemplateClass<T> {
: public T newInstance() {
: new T(); << 這裡會有問題,想問這邊該如何改可以達到我想要的效果
: }
: }
: ※ 引述《tgbsa (每天進步一點點)》之銘言:
: : 程式碼如下:
: : public class z {
: : public static void main(String[] argv)
: : {
: : //String[] s = (String[])new Object[10];
: : ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
: 剛剛測試是可以通過編譯,但是會有 Warning
這裡是可以通過編譯沒錯,應該不會有Warning,只是Runtime時一定會丟
出ClassCastException
: : SimpleCollection<String> Sim = new SimpleCollection<String>();
: : }
: : }
: : class SimpleCollection<T>
: : {
: : private T[] objArr;
: : public SimpleCollection()
: : {
: : objArr = (T[]) new Object[10];
: : ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
: 這行一樣也會有 Warning
: : }
: : }
: : 請問板上眾多高手!上面那兩行有什麼不同?
: : 依照我的觀念是,SimpleCollection中在compile time的時候會被取代為
: : private String[] objArr;
: : public SimpleCollection()
: : {
: : objArr = (String[]) new Object[10];
: : ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
但是這裡編譯時會出現
Note: Test.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
這樣的訊息告知可能是不安全的操作
雖然如此,但是卻可以正常執行!!我的問題癥結就在這
: : }
: : 但是這樣看起來怪怪的!? String型態的陣列參考指向Object!?
: : 這樣可以編譯並執行不會丟出例外!?
: : 但是在main中的那個我注解的statment並沒有辦法順利編譯~!這是為什麼原因阿?
: : 是泛型類別中有什麼樣的特性我沒注意到嗎?
: : 來補上完整程式碼好了
: : class Test
: : {
: : public static void main(String[] args)
: : {
: : SimpleCollection<Integer> c = new SimpleCollection<Integer>();
: : for(int i = 0; i < 10; i++)
: : {
: : c.add(new Integer(i));
: : }
: : for(int i = 0; i < 10; i++)
: : {
: : Integer k = c.get(i);
: : }
: : }
: : }
: : class SimpleCollection<T> {
: : private T[] objArr;
: : private int index = 0;
: : public SimpleCollection()
: : {
: : objArr = (T[]) new Object[10]; //問題在這
: : }
: : public SimpleCollection(int capacity)
: : {
: : objArr = (T[]) new Object[capacity]; //還有這
: : }
: : public void add(T t)
: : {
: : objArr[index] = t;
: : index++;
: : }
: : public int getLength()
: : {
: : return index;
: : }
: : public T get(int i)
: : {
: : return (T) objArr[i];
: : }
: : }
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 118.170.0.173
推
06/03 03:39, , 1F
06/03 03:39, 1F
→
06/03 03:42, , 2F
06/03 03:42, 2F
推
06/03 03:47, , 3F
06/03 03:47, 3F
推
06/03 19:44, , 4F
06/03 19:44, 4F
討論串 (同標題文章)