



使用泛型的好处:不必在使用Collection接口及其子接口操作数据的时候,一直对Object数据进行强制转换
List在定义时就规定了泛型,所以存入取出的时候类型都是既定的Course类型
- Course.java
package com.collection;
/**
* 课程类
* @author my-mac
*
*/
public class Course {
public String id;
public String name;
/**
* 当此无参构造器没有实现的时候
* 继承此类的子类将会报错:Implicit super constructor Course() is undefined for default constructor.
* Must define an explicit constructor
* 原因:继承此类的子类,必须要隐式的调用无参的构造器。
* 但是此类声明了有参构造器,所以不会生成隐式的构造器,需要手动生成一个显式的无参构造器
*/
public Course() {
// TODO Auto-generated constructor stub
}
public String getId() {
return id;
}
public void setId(String id) {
if(id == ""){
System.out.println("请输入id");
}else{
this.id = id;
}
}
public String getName() {
return name;
}
public void setName(String name) {
if(name == ""){
System.out.println("请输入name");
}else{
this.name = name;
}
}
public Course(String id, String name){
this.setId(id);
this.setName(name);
}
}
- ChildCourse.java
package com.collection;
public class ChildCourse extends Course {
}
- TestGeneric.java
package com.collection;
import java.util.ArrayList;
import java.util.List;
public class TestGeneric {
/**
* 带有泛型Course的List类型的属性
*/
public List<Course> course;
public TestGeneric(){
this.course = new ArrayList<Course>();
}
public void testAdd() {
Course cr1 = new Course("1", "语文");
course.add(cr1);
/**
* 报错:The method add(Course) in the type List<Course> is not applicable for the arguments (String)
* 原因:泛型集合中,不能添加泛型规定的类型及其子类型以外的对象
* course.add("能否添加一些奇怪的东西呢?");
*/
Course cr2 = new Course("2", "java基础");
course.add(cr2);
}
public void testForEach(){
// 在泛型
for (Course cr : course) {
System.out.println(cr.id + ":" + cr.name);
}
}
/**
* 泛型集合可以添加泛型的子类型的对象的实例
* @param args
*/
public void testChild(){
ChildCourse ccr = new ChildCourse();
ccr.id = "3";
ccr.name = "我是子类型的课程对象实例~~";
course.add(ccr);
}
/**
* 泛型不能使用基本类型
* @param args
*/
public void testBasicType(){
/**
* 报错:Multiple markers at this line
* - Syntax error, insert "Dimensions" to complete ReferenceType
* - Syntax error, insert "Dimensions" to complete ReferenceType
* List<int> list = new ArrayList<int>();
*/
List<Integer> list = new ArrayList<Integer>();
// 这里 int 类型的1被强制转换成了Int的包装类Integer,然后被加入到集合
list.add(1);
System.out.println("基本类型必须使用包装类型作为泛型:" + list.get(0));
}
public static void main(String[] args) {
// TODO Auto-generated method stub
TestGeneric tg = new TestGeneric();
tg.testAdd();
tg.testForEach();
tg.testChild();
tg.testForEach();
tg.testBasicType();
}
}

网友评论