-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathGenericArray2.java
More file actions
55 lines (40 loc) · 1.12 KB
/
GenericArray2.java
File metadata and controls
55 lines (40 loc) · 1.12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
package generics;
import java.util.*;
/**
* RUN:
* javac generics/GenericArray2.java && java generics.GenericArray2
* OUTPUT:
* 0 1 2 3 4 5 6 7 8 9
* java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.Integer;
*/
public class GenericArray2<T> {
private Object[] array;
public GenericArray2(int size) {
array = new Object[size];
}
public void put(int index, T item) {
array[index] = item;
}
@SuppressWarnings("unchecked")
public T get(int index) {
return (T)array[index];
}
@SuppressWarnings("unchecked")
public T[] rep() { return (T[])array; }
public static void main(String[] args) {
GenericArray2<Integer> gai = new GenericArray2<Integer>(10);
for (int i = 0; i < 10; i++) {
gai.put(i, i);
}
for (int i = 0; i < 10; i++) {
System.out.print(gai.get(i) + " ");
}
System.out.println();
try {
Integer[] a = gai.rep();
}
catch (Exception e) {
System.out.println(e);
}
}
}