Chinaunix首页 | 论坛 | 博客
  • 博客访问: 42559
  • 博文数量: 71
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 726
  • 用 户 组: 普通用户
  • 注册时间: 2014-11-24 08:29
文章分类

全部博文(71)

文章存档

2015年(71)

我的朋友

分类: Java

2015-02-15 23:01:25


  1. package com.imooc.collection;

  2. import java.util.ArrayList;
  3. import java.util.List;

  4. public class TestGeneric {

  5.     /*
  6.      * 带有泛型--Course的List类型属性
  7.      */
  8.     public List<Course> courses;

  9.     public TestGeneric() {
  10.         this.courses = new ArrayList<Course>();// 调用了构造方法
  11.     }

  12.     /**
  13.      * 测试添加
  14.      *
  15.      * @param args
  16.      */

  17.     public void testAdd() {
  18.         Course cr1 = new Course("1", "大学语文");
  19.         courses.add(cr1);
  20.         /*
  21.          * // The method add(Course) in the type List is not applicable
  22.          * for // the arguments (String) courses.add("能否添加一个奇怪的东西呢?");
  23.          */
  24.         Course cr2 = new Course("2", "Java基础");
  25.         courses.add(cr2);

  26.     }

  27.     /**
  28.      * 测试循环遍历
  29.      *
  30.      * @param args
  31.      */

  32.     public void testForEach() {
  33.         // 泛型的一大好处:直接Course类型
  34.         for (Course cr : courses) {
  35.             System.out.println(cr.id + ":" + cr.name);
  36.         }
  37.     }

  38.     /**
  39.      * 泛型结合可以添加的子类型的对象实例
  40.      */
  41.     public void testChild(){
  42.         ChildCourse ccr = new ChildCourse();
  43.         ccr.id = "3";
  44.         ccr.name = "我是子类型的课程对象实例";
  45.         courses.add(ccr);
  46.     }
  47.     public static void main(String[] args) {
  48.         TestGeneric tg = new TestGeneric();
  49.         tg.testAdd();
  50.         tg.testForEach();
  51.         tg.testChild();
  52.         tg.testForEach();
  53.     }

  54. }

新建一个类,继承于Course

  1. package com.imooc.collection;

  2. public class ChildCourse extends Course {
  3.     
  4. }


  1. package com.imooc.collection;

  2. /**
  3.  * 课程类
  4.  *
  5.  * @author
  6.  *
  7.  */
  8. public class Course {

  9.     public String id;
  10.     public String name;

  11.     public Course(String id, String name) {
  12.         this.id = id;
  13.         this.name = name;
  14.     }
  15.     
  16.     public Course(){
  17.         
  18.     }
  19. }

PS:
        1.泛型集合中的限定类型不能使用基本数据类型。可以使用它们的包装类才行

  1. public void testBasicType(){
  2.       List<Integer> list = new ArrayList<Integer>();
  3. }
阅读(128) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~