-
package com.imooc.collection;
-
-
import java.util.ArrayList;
-
import java.util.List;
-
-
public class TestGeneric {
-
-
/*
-
* 带有泛型--Course的List类型属性
-
*/
-
public List<Course> courses;
-
-
public TestGeneric() {
-
this.courses = new ArrayList<Course>();// 调用了构造方法
-
}
-
-
/**
-
* 测试添加
-
*
-
* @param args
-
*/
-
-
public void testAdd() {
-
Course cr1 = new Course("1", "大学语文");
-
courses.add(cr1);
-
/*
-
* // The method add(Course) in the type List is not applicable
-
* for // the arguments (String) courses.add("能否添加一个奇怪的东西呢?");
-
*/
-
Course cr2 = new Course("2", "Java基础");
-
courses.add(cr2);
-
-
}
-
-
/**
-
* 测试循环遍历
-
*
-
* @param args
-
*/
-
-
public void testForEach() {
-
// 泛型的一大好处:直接Course类型
-
for (Course cr : courses) {
-
System.out.println(cr.id + ":" + cr.name);
-
}
-
}
-
-
/**
-
* 泛型结合可以添加的子类型的对象实例
-
*/
-
public void testChild(){
-
ChildCourse ccr = new ChildCourse();
-
ccr.id = "3";
-
ccr.name = "我是子类型的课程对象实例";
-
courses.add(ccr);
-
}
-
public static void main(String[] args) {
-
TestGeneric tg = new TestGeneric();
-
tg.testAdd();
-
tg.testForEach();
-
tg.testChild();
-
tg.testForEach();
-
}
-
-
}
新建一个类,继承于Course
-
package com.imooc.collection;
-
-
public class ChildCourse extends Course {
-
-
}
-
package com.imooc.collection;
-
-
/**
-
* 课程类
-
*
-
* @author
-
*
-
*/
-
public class Course {
-
-
public String id;
-
public String name;
-
-
public Course(String id, String name) {
-
this.id = id;
-
this.name = name;
-
}
-
-
public Course(){
-
-
}
-
}
![](/attachment/201502/15/30035714_1424012101qHqo.jpg)
PS:
1.泛型集合中的限定类型不能使用基本数据类型。可以使用它们的包装类才行
-
public void testBasicType(){
-
List<Integer> list = new ArrayList<Integer>();
-
}
阅读(128) | 评论(0) | 转发(0) |