
- 泛型,又叫参数化类型,解决数据类型安全性问题
- 类声明和实例化指定需要的类型
- 保证程序编译没有警告,运行就没有ClassCastExcetion异常,代码简洁健壮
- 在类声明通过一个标识类中某个属性的类型,或方法返回值类型,参数类型
public class ge01 {
public static void main(String[] args) {
Person p = new Person<>("jack");
System.out.println(p.getE());
p.show();
}
}
class Person{
E e;
public Person(E e) {
this.e = e;
}
public E getE() {
return e;
}
public void show(){
System.out.println(e.getClass());
}
}
细节
自定义泛型类
public class ge01 {
public static void main(String[] args) {
Person p = new Person<>("jack");
System.out.println(p.getE());
p.show();
}
}
class Person{
E e;
public Person(E e) {
this.e = e;
}
public E getE() {
return e;
}
public void show(){
System.out.println(e.getClass());
}
}
自定义泛型接口
public static void main(String[] args) {
ge03 ge03 = new ge03();
ge03.hi("ji");
ge03.hello(34);
}
@Override
public void hi(String o) {
System.out.println(o);
}
@Override
public void hello(Integer integer) {
a.super.hello(integer);
}
}
interface a{
//E e;接口中不能使用静态属性泛型
void hi(E e);
default void hello(V v){
System.out.println(v);
}
}
自定义泛型方法
public static void main(String[] args) {
ge04 objectge04 = new ge04<>();
objectge04.show(3);
objectge04.show1(7.2);
}
public void show(M m){
System.out.println(m);
}//自定义泛型方法
public void show1(E e){
System.out.println(e);
}//泛型在方法中的使用
}
泛型继承和通配符>
public static void main(String[] args) {
ArrayList list = new ArrayList<>();
ArrayList arrayList = new ArrayList<>();
ArrayList aas = new ArrayList<>();
ArrayList bs = new ArrayList();
ArrayList ccs = new ArrayList<>();
ge05 ge05 = new ge05();
ge05.p(list);
ge05.p(arrayList);
ge05.p(aas);
ge05.p(bs);
ge05.p(ccs);
//只能是BB或其子类CC
//ge05.q(list);
//ge05.q(arrayList);
//ge05.q(aas);
ge05.q(bs);
ge05.q(ccs);
//只能是BB或其父类AA
//ge05.r(list);
//ge05.r(arrayList);
ge05.r(aas);
ge05.r(bs);
//ge05.r(ccs);
}
void p(List> c){}
void q(List extends BB> q){}
void r(List super BB> r){}
}
class AA{}
class BB extends AA{}
class CC extends BB{}
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)