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

JAVA学习笔记(五十六)- 泛型 Generic Types

2015-04-05 14:22 211 查看

泛型 Generic Types

import java.util.ArrayList;
import java.util.List;

/*
* 泛型 Generic Types
* 集合泛型
* 类泛型
* 方法泛型
*/
public class Test01 {
public static void main(String[] args) {
// 1.集合泛型,保证集合中元素的类型安全
List<Integer> nums = new ArrayList<Integer>();
nums.add(25);
// nums.add("tom"); //只能添加整型数值

// 2.类泛型
Student stu1 = new Student("tom");
stu1.obj = 25; // Object无法保证类型的安全
stu1.show();

//创建泛型类的对象时需要指定具体的数据类型,保证数据安全
Student2<String> stu2=new Student2<String>("jack");
//stu2.t=38;
stu2.show();

// 3.方法泛型
print("tom");
print(20);
print(13.5);

}

public static <T> void print(T t){
System.out.println(t.getClass());
}
}

/*
* 普通的类
*/
class Student {
Object obj;

public Student(Object obj) {
this.obj = obj;
}

public void show() {
System.out.println(obj);
}
}

/*
* 泛型类
*/
class Student2<T> {
T t;

public Student2(T t) {
this.t = t;
}

public void show(){
System.out.println(t);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息