程序三:主要说明在对象中通过用Object[]来保存数据,则生成对象是,可以对其持有的对象在T和object之间进行转换,但是当设计到数组的转换时,还是会报ClassCastException
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- public class ArrayOfGeneric3<T> {
- Object[] ts;
-
- public ArrayOfGeneric3(int size) {
- ts = new Object[size];
- }
-
- public T get(int index) {
- return (T) ts[index];
- }
-
- public T[] rep() {
- return (T[]) ts;
- }
-
- public void set(int index, T t) {
- ts[index] = t;
- }
-
- public static void main(String[] args) {
- ArrayOfGeneric3<Integer> aog2 = new ArrayOfGeneric3<Integer>(10);
- Object[] objs = aog2.rep();
- for (int i = 0; i < 10; i++) {
- aog2.set(i, i);
- System.out.println(aog2.get(i));
- }
- Integer[] strs = aog2.rep();
- System.out.println(strs);
- }
- }
|
程序四:是对泛型数组相对而言比较完美的解决方案
-
-
-
-
-
-
-
-
-
-
-
- public class ArrayOfGeneric4<T> {
-
- T[] ts;
-
- public ArrayOfGeneric4(Class<T> type, int size) {
-
- ts = (T[]) Array.newInstance(type, size);
- }
-
- public T get(int index) {
- return ts[index];
- }
-
- public T[] rep() {
- return ts;
- }
-
- public void set(int index, T t) {
- ts[index] = t;
- }
-
- public static void main(String[] args) {
- ArrayOfGeneric4<Integer> aog2 = new ArrayOfGeneric4<Integer>(Integer.class, 10);
- Object[] objs = aog2.rep();
- for (int i = 0; i < 10; i++) {
- aog2.set(i, i);
- System.out.println(aog2.get(i));
- }
- try {
- Integer[] strs = aog2.rep();
- System.out.println("user Array.newInstance to create generci of array was successful!!!!! ");
- } catch (Exception ex) {
- ex.printStackTrace();
- }
- }
- }
|
泛型这一章节的内容从擦除开始,觉得都是非常的难懂,如果哪位同志有比较好的建议,希望能不惜指教!
