不使用泛型
package test
;
public class testGeneric {
public static void main(String
[] args
) {
myCollection mc
= new myCollection();
mc
.set("硕鼠", 0);
mc
.set(998, 1);
Integer a
= (Integer
)mc
.get(1);
String b
= (String
)mc
.get(0);
System
.out
.println(a
);
System
.out
.println(b
);
}
}
class myCollection{
Object
[] objs
= new Object[5];
public void set(Object obj
, int index
) {
objs
[index
] = obj
;
}
public Object
get(int index
) {
return objs
[index
];
}
}
泛型类的声明
class myCollection<E>{
Object
[] es
= new Object[5];
public void set(E e
, int index
) {
es
[index
] = e
;
}
public E
get(int index
) {
return (E
)es
[index
];
}
}
我们可以在类的声明处增加泛型列表,如:<T,E,V>。
此处,字符可以是任何标识符,一般采用这3个字母。
泛型类的应用
package cn
.yzy
.collection
;
public class testGeneric01 {
public static void main(String
[] args
) {
myCollection
<String> mc
= new myCollection<String>();
mc
.set("硕鼠", 0);
mc
.set("硕喵", 1);
String a
= mc
.get(1);
String b
= mc
.get(0);
System
.out
.println(a
);
System
.out
.println(b
);
}
}
class myCollection<E>{
Object
[] es
= new Object[5];
public void set(E e
, int index
) {
es
[index
] = e
;
}
public E
get(int index
) {
return (E
)es
[index
];
}
}
转载请注明原文地址:https://ipadbbs.8miu.com/read-18302.html