Skip to content

Commit f2be3e8

Browse files
committed
first edition
1 parent ca5550b commit f2be3e8

File tree

1 file changed

+77
-0
lines changed

1 file changed

+77
-0
lines changed
Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
如何创建一个java泛型数组
2+
问题:
3+
由于Java泛型的实现机制,你不能这样写代码:
4+
pulic class GenSet<E>{
5+
private E a[];
6+
public GetSet(){
7+
a=new E[INITIAL_ARRAY_LENGTH]; //error:generic array creation
8+
}
9+
}
10+
在保证类型安全的情况下,我该如何实现创建一个Java泛型数组?
11+
我在一个Java论坛上看到是这样解决的:
12+
import java.lang.reflect.Array;
13+
14+
class Stack<T> {
15+
public Stack(Class<T> clazz, int capacity) {
16+
array = (T[])Array.newInstance(clazz, capacity);
17+
}
18+
19+
private final T[] array;
20+
}
21+
但我不懂发生了什么。有人能帮我吗?
22+
23+
回答:
24+
在回答之前,我得问你一个问题,你的GetSet是"checked"还是"unchecked"?
25+
什么意思呢?
26+
Checked的话,是强类型。GetSet明确地知道包含了什么类型的对象。
27+
比如,当要传递不是E类型的实参时,它的构造器会被Class<E>引数明确地调用,方法会抛出一个异常。参阅Collections.checkedCollection。
28+
在这种情况下,你应该这样写:
29+
public class GenSet<E> {
30+
31+
private E[] a;
32+
33+
public GenSet(Class<E> c, int s) {
34+
// Use Array native method to create array
35+
// of a type only known at run time
36+
@SuppressWarnings("unchecked")
37+
final E[] a = (E[]) Array.newInstance(c, s);
38+
this.a = a;
39+
}
40+
41+
E get(int i) {
42+
return a[i];
43+
}
44+
}
45+
Unchecked的话:弱类型。实际上要传递任何对象的实参时
46+
是没有类型检查的。
47+
在这种情况下,你应当这样写:
48+
public class GenSet<E> {
49+
50+
private Object[] a;
51+
52+
public GenSet(int s) {
53+
a = new Object[s];
54+
}
55+
56+
E get(int i) {
57+
@SuppressWarnings("unchecked")
58+
final E e = (E) a[i];
59+
return e;
60+
}
61+
}
62+
注意数组里的元素类型应当是可擦除的形参。
63+
public class GenSet<E extends Foo> { // E has an upper bound of Foo
64+
65+
private Foo[] a; // E erases to Foo, so use Foo[]
66+
67+
public GenSet(int s) {
68+
a = new Foo[s];
69+
}
70+
71+
...
72+
}
73+
所有的这些结果来自Java一个有名,存心,不足的泛型:它通过使用
74+
erasure实现,所以“泛型”类在运行时创建是不知道它的实参类型的,
75+
所以不能提供类型安全,除非某些明确的机制(比如类型检查)已经实现了。
76+
StackOverflow地址:
77+
http://stackoverflow.com/questions/529085/how-to-create-a-generic-array-in-java

0 commit comments

Comments
 (0)