javaSe-泛型

泛型就是在实例化对象的时候在为其指定类型,平时用的很少,但是在做框架的时候却在大量的使用,所以架构师很吊的,

下面代码中c1、c2、c3都是通过比较以及多台来实现 泛型,多台实现的原理是Objice类是所有类的祖先,但是实现起来会有很多向上或者向下转型的不方便的地方,所以我们就引入的真正的泛型

 -1创建C1

package com.java.chap06.sec01;

public class C1 {

private Integer a;

public C1(Integer a) {
super();
this.a = a;
}

public Integer getA() {
return a;
}

public void setA(Integer a) {
this.a = a;
}

public void print(){
System.out.println("a的类型是:"+a.getClass().getName());
}
}

-2创建C2

package com.java.chap06.sec01;

public class C2 {

private String a;

public C2(String a) {
super();
this.a = a;
}

public String getA() {
return a;
}

public void setA(String a) {
this.a = a;
}

public void print(){
System.out.println("a的类型是:"+a.getClass().getName());
}

-3.创建C12

package com.java.chap06.sec01;

public class C12 {

private Object object;

public C12(Object object) {
super();
this.object = object;
}

public Object getObject() {
return object;
}

public void setObject(Object object) {
this.object = object;
}

public void print(){
System.out.println("object的类型是:"+object.getClass().getName());
}

}

-4创建cc

package com.java.chap06.sec01;

public class CC<T> {

private T t;

public CC(T t) {
super();
this.t = t;
}

public T getT() {
return t;
}

public void setT(T t) {
this.t = t;
}

public void print(){
System.out.println("t的类型是:"+t.getClass().getName());
}

}

-5创建测试类

package com.java.chap06.sec01;

public class Test {

public static void main(String[] args) {
// begin test c1 c2
C1 c1=new C1(1);
c1.print();
int i=c1.getA();
System.out.println("i="+i);

C2 c2=new C2("Hi");
c2.print();
String s=c2.getA();
System.out.println("s="+s);
// end test c1 c2

// begin test c12
C12 c12=new C12(1); // 向上转型
c12.print();
int i2=(Integer) c12.getObject(); // 向下转型
System.out.println("i2="+i2);

C12 c122=new C12("你好");
c122.print();
String s2=(String) c122.getObject();
System.out.println("s2="+s2);
// end test c12

// begin test cc
CC<Integer> cc=new CC<Integer>(1);
cc.print();
int i3=cc.getT();
System.out.println("i3="+i3);

CC<String> cc2=new CC<String>("我是泛型,好简单");
cc2.print();
String s3=cc2.getT();
System.out.println("s3="+s3);
// end test cc
}
}

2.泛型方法

public class Test {

/**
* 泛型方法
* @param t
*/
public static <T> void f(T t){
System.out.println("T的类型是:"+t.getClass().getName());
}

public static void main(String[] args) {
f("");
f(1);
f(1.0f);
f(new Object());
}
}



}

posted @ 2017-03-01 07:26  小拽A  阅读(161)  评论(0编辑  收藏  举报