泛型
增加不同于课程类型的数据
/imooc_collection_map_demo/src/com/imooc/collection/ListTest.java
public void testType() {
System.out.println("往list里增加字符串");
coursesToSelect.add("字符串");
}
public static void main(String[] args) {
ListTest lt = new ListTest();
lt.testType();
lt.testForEach();
}
泛型实现
/imooc_collection_map_demo/src/com/imooc/collection/TestGeneric.java
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>();
}
//添加
public void testAdd() {
Course cr1 = new Course("1","大学语文");
courses.add(cr1);
Course cr2 = new Course("2", "java基础");
courses.add(cr2);
}
//循环遍历
public void testForEach() {
for(Course cr: courses) {
System.out.println(cr.id + ":" + cr.name);
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
TestGeneric tg = new TestGeneric();
tg.testAdd();
tg.testForEach();
}
}
泛型子类型
/imooc_collection_map_demo/src/com/imooc/collection/ChildCourse.java
package com.imooc.collection;
public class ChildCourse extends Course {
}
红色报错
解决办法
添加无参的构造方法
/imooc_collection_map_demo/src/com/imooc/collection/Course.java
泛型集合可以添加泛型的子类型的对象实例
/imooc_collection_map_demo/src/com/imooc/collection/TestGeneric.java
public void testChild() {
ChildCourse ccr = new ChildCourse();
ccr.id = "3";
ccr.name = "我是子类型的课程对象实例";
courses.add(ccr);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
TestGeneric tg = new TestGeneric();
tg.testChild();
tg.testForEach();
}
泛型不能使用基本类型
/imooc_collection_map_demo/src/com/imooc/collection/TestGeneric.java
public void testBasicType() {
List<Integer> list = new ArrayList<Integer>();
list.add(1);
System.out.println("基本类型必须使用包装类作为泛型 " + list.get(0));
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。