作者tgbsa (每天进步一点点)
看板java
标题Re: [问题] 泛型类别...
时间Tue Jun 3 02:46:02 2008
※ 引述《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
1F:推 chordee:erasure特性 T在里面会被MIB闪到失忆 忘记自己的类型 06/03 03:39
2F:→ chordee:把一个Class<T>传进去 用它建立一个正确类型的Array 06/03 03:42
3F:推 chordee:(T[])Array.newInstance(Class<T>,int)这样类型就抓回来了 06/03 03:47
4F:推 ClareQ:用reflection来建立阵列会比较慢一点,不过没其他办法XD 06/03 19:44