作者csihcs (非天夜翔)
站内java
标题Re: [问题] 泛型类别...
时间Tue Jun 3 01:05:52 2008
另外我想借标题问如何在 template 中,new 出实体?
class Test {
public static void main(String[] argv) {
TemplateClass<String> ts = new TemplateClass<String>;
String s = ts.newInstance();
}
}
class TemplateClass<T> {
public T newInstance() {
return new T();
<< 这里会有问题,想问这边该如何改可以达到我想要的效果
}
}
※ 引述《tgbsa (每天进步一点点)》之铭言:
: 程式码如下:
: public class z {
: public static void main(String[] argv)
: {
: //String[] s = (String[])new Object[10];
: ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
刚刚测试是可以通过编译,但是会有 Warning
: 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];
: ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
: }
: 但是这样看起来怪怪的!? 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: 59.104.31.180
1F:推 TonyQ:没有return ? 06/03 02:04
2F:推 tgbsa:1.没main method 2.new TemplateClass<String>()<-忘了打 06/03 03:35
3F:→ tgbsa:3.new T()并非所有的建构元型式都是这样 06/03 03:37
※ 编辑: csihcs 来自: 59.104.31.180 (06/03 11:35)