Skip to content

Commit 01ca924

Browse files
committed
update->junit4 && add->create_generic_array
1 parent 6280541 commit 01ca924

2 files changed

+77
-1
lines changed

contents/how-do-you-assert-that-a-certain-exception-is-thrown-in-junit-4-tests.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
## JUnit如何断言一个确定的异常抛出
1+
## JUnit4如何断言确定异常的抛出
22

33
#### 问题
44

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
## 如何创建泛型java数组
2+
3+
#### 问题
4+
5+
数组是不能通过泛型创建的,因为我们不能创建不可具体化的类型的数组。如下面的代码:
6+
7+
```java
8+
public class GenSet<E> {
9+
private E a[];
10+
11+
public GenSet() {
12+
a = new E[INITIAL_ARRAY_LENGTH]; //编译期就会报错:不能创建泛型数组
13+
}
14+
}
15+
```
16+
17+
#### 采纳答案
18+
19+
* 检查:强类型。`GenSet`明确知道数组中包含的类型是什么(例如通过构造器传入`Class<E>`,当方法中传入类型不是`E`将抛出异常)
20+
21+
```java
22+
public class GenSet<E> {
23+
24+
private E[] a;
25+
26+
public GenSet(Class<E> c, int s) {
27+
// 使用原生的反射方法,在运行时知道其数组对象类型
28+
@SuppressWarnings("unchecked")
29+
final E[] a = (E[]) Array.newInstance(c, s);
30+
this.a = a;
31+
}
32+
33+
E get(int i) {
34+
return a[i];
35+
}
36+
37+
//...如果传入参数不为E类型,那么强制添加进数组将会抛出异常
38+
void add(E e) {...}
39+
}
40+
```
41+
42+
* 未检查:弱类型。数组内对象不会有任何类型检查,而是作为Object类型传入。
43+
44+
在这种情况下,你可以采取如下写法:
45+
46+
```java
47+
public class GenSet<E> {
48+
49+
private Object[] a;
50+
51+
public GenSet(int s) {
52+
a = new Object[s];
53+
}
54+
55+
E get(int i) {
56+
@SuppressWarnings("unchecked")
57+
final E e = (E) a[i];
58+
return e;
59+
}
60+
}
61+
```
62+
63+
上述代码在编译期能够通过,但因为泛型擦除的缘故,在程序执行过程中,数组的类型有且仅有`Object`类型存在,这个时候如果我们强制转化为`E`类型的话,在运行时会有`ClassCastException`抛出。所以,要确定好泛型的上界,将上边的代码重写一下:
64+
65+
```java
66+
public class GenSet<E extends Foo> { // E has an upper bound of Foo
67+
68+
private Foo[] a; // E 泛型在运行期会被擦除为Foo类型,所以这里使用Foo[]
69+
70+
public GenSet(int s) {
71+
a = new Foo[s];
72+
}
73+
74+
//...
75+
}
76+
```

0 commit comments

Comments
 (0)