您的位置:首页 > 编程语言 > Java开发

Java泛型总结

2015-08-19 22:59 781 查看
1、泛型主要是用来年解决数据类型安全的问题,用标识来代替属性的类型或者返回值的类型

2、在使用泛型的时候可以有以下几种形式:

泛型接口

泛型类

通配符做泛型参数

泛型方法

泛型数组

3、以下通过代码说明:

package com.sun.demo;

//一、定义泛型接口
interface Father <T> {
public void say();
}
//二、定义泛型类
//三、多泛型情况

class son<T ,K> implements Father<T>{

private T task ;
private K kit ;

public son (T task,K kit){
this .task = task;
this .kit = kit;
}

public son(){

}

public void setKit(K kit) {
this .kit = kit;
}
public K getKit() {
return kit ;
}

public void setTask(T task) {
this .task = task;
}

public T getTask() {
return task ;
}

@Override
public void say() {
//输出相应泛型对象的时候最好重写toString方法
System. out .println(this .getTask());
System. out .println(this .getKit());
}

}

public class Geneic1 {

public static void main(String[] args) {

son<String, String> son1 = new son<String, String>();
son1.setKit( "K" );
son1.setTask( "T" );
callSon(son1);
son<String , Integer> son = new son<String , Integer>();
son.setTask( "son" );
son.setKit(100);
son.say();
System. out .println(show( "String" ));

Double arr[]  = {1.2 , 3.0 , 4.5};
showArrays(arr);
}

public static <T>T show( T t){
return t;
}
//四、声明泛型方法,注意其格式
//1、返回值前加泛型
//2、参数为泛型
public static <T> void showArrays(T arrays[]){
for (int i = 0; i < arrays. length; i++) {
System. out .println(arrays[i]);
}
}
//五、对象中的泛型不明确时用通配符?代替
public static void callSon(son<? , ?> i){
i.say();
}
}


4、多泛型时候的注意事项:

class Demo<T , S extends T>{}


这样可以声明多泛型之间的关系

5、泛型的其他注意事项:

泛型不是异变的,这也是泛型是安全的原因,即声明好一个泛型方法之后,其参数即为固定如

public void say(myclass s)之后不能通过 myclass 类型的参数调用say方法,此时编译不会通过

泛型不止可在容器中使用,见以上
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: