黑马程序员--泛型与集合框架

--------- android培训java培训期待与您交流 ----------

4 泛型在集合中的使用

4.1泛型介绍

  1,在Java SE 1.5之前,没有泛型的情况的下,通过对类型Object的引用来实现参数的“任意化”,“任意化”带来的缺点是要做显式的强制类型转换,而这种转换是要求开发者对实际参数类型可以预知的情况下进行的。对于强制类型转换错误的情况,编译器可能不提示错误,在运行的时候才出现异常,这是一个安全隐患。JDK1.5版本以后出现新特性,用来解决安全问题,是一个类型安全机制。

  2,泛型的好处:

  •  将运行时期出现问题ClassCastException,转移到了编译时期。 方便于程序员解决问题。让运行时问题减少,安全。,
  •  避免了强制转换麻烦。

  3,泛型格式:通过<>来定义要操作的引用数据类型

  4,什么时候使用泛型?

  •  通常在集合框架中很常见,只要见到<>就要定义泛型。
  •  其实<> 就是用来接收类型的。
  •  当使用集合时,将集合中要存储的数据类型作为参数传递到<>中即可。

4.2 泛型的使用

 1,  ArrayList<String> al = new ArrayList<String>();//该集合中只能存入String类型的数据。

遍历存入ArrayList集合中元素并输出对应元素的长度。

GenericDemo
 1 import java.util.*;
 2 
 3 
 4 class GenericDemo 
 5 {
 6     public static void main(String[] args) 
 7     {
 8 
 9         ArrayList<String> al=new ArrayList<String>();//规定了只能存入String类型数据
10         
11         al.add("abcd234");
12         al.add("abcd234567");
13         al.add("abcd2346789");
14         
15         Iterator<String> it = al.iterator();
16         while(it.hasNext())
17         {
18             String s = it.next();
19 
20             System.out.println(s+":"+s.length());
21         }
22     }
23 }

2,TreeSet<String> ts = new TreeSet<String>(new LenComparator());

 比较元素的长度并按长度降序排列。当长度相同的元素,按自然顺序的倒序排列。

 

TreeSet泛型使用
 1 import java.util.*;
 2 class GenericDemo2 
 3 {
 4     public static void main(String[] args) 
 5     {
 6         //按比较器比较元素的长度并输出,
 7         TreeSet<String> ts = new TreeSet<String>(new LenComparator());
 8         
 9         //添加元素,元素只能是String类型
10         ts.add("abcd");
11         ts.add("cc");
12         ts.add("cba");
13         ts.add("aaa");
14         ts.add("z");
15         ts.add("hahaha");
16 
17         //迭代器遍历元素,迭代器数据类型必须和集合的数据类型一致
18         Iterator<String> it = ts.iterator();
19 
20         while(it.hasNext())
21         {
22             String s = it.next();
23             System.out.println(s);
24         }
25     }
26 }
27 //同样比较器也使用了泛型,且数据类型与集合的数据类型保持一致。
28 class LenComparator implements Comparator<String>
29 {
30     public int compare(String o1,String o2)
31     {
32         int num = new Integer(o2.length()).compareTo(new Integer(o1.length()));
33 
34         if(num==0)
35             return o2.compareTo(o1);
36         return num;
37     }
38 }

3,泛型类的使用

什么时候定义泛型类?
当类中要操作的引用数据类型不确定的时候,
早期定义Object来完成扩展。
现在定义泛型来完成扩展。

 

泛型类示例
/*
class Tool
{
    private Worker w;
    public void setWorker(Worker w)
    {
        this.w = w;
    }
    public Worker getWorker()
    {
        return w;
    }
}
*/

class Worker
{

}
class Student
{
}
//泛型前做法。
class Tool
{
    private Object obj;
    public void setObject(Object obj)
    {
        this.obj = obj;
    }
    public Object getObject()
    {
        return obj;
    }
}

//泛型类。
/*
什么时候定义泛型类?
当类中要操作的引用数据类型不确定的时候,
早期定义Object来完成扩展。
现在定义泛型来完成扩展。
*/
class Utils<QQ>
{
    private QQ q;
    public void setObject(QQ q)
    {
        this.q = q;
    }
    public QQ getObject()
    {
        return q;
    }
}


class  GenericDemo3
{
    public static void main(String[] args) 
    {

        Utils<Worker> u = new Utils<Worker>();

        u.setObject(new Worker());
        //u.setObject(new student());//把错误在编译时显示出来
        Worker w = u.getObject();//不用再强制转换
        /*
        Tool t = new Tool();
        t.setObject(new Student());
        Worker w = (Worker)t.getObject();
        */
    }
}

4,泛型方法的使用

  • 泛型类定义的泛型,在整个类中有效。如果被方法使用,
  • 那么泛型类的对象明确要操作的具体类型后,所有要操作的类型就已经固定了。

 

  • 为了让不同方法可以操作不同类型,而且类型还不确定。
  • 那么可以将泛型定义在方法上。

 

  • 特殊之处:

  静态方法不可以访问类上定义的泛型。
  如果静态方法操作的应用数据类型不确定,可以将泛型定义在方法上。

泛型方法示例
 1 class Demo<T>
 2 {
 3     //不同方法可以操作不同类型,同一个方法也可以操作不同类型
 4     public  void show(T t)
 5     {
 6         System.out.println("show:"+t);
 7     }
 8     public <Q> void print(Q q)
 9     {
10         System.out.println("print:"+q);
11     }
12     public  static <W> void method(W t)
13     {
14         System.out.println("method:"+t);
15     }
16 }
17 class GenericDemo4 
18 {
19     public static void main(String[] args) 
20     {
21         Demo <String> d = new Demo<String>();
22         d.show("haha");
23         //d.show(4);
24         d.print(5);
25         d.print("hehe");
26 
27         Demo.method("xixixixiixi");
28 
29         /*
30         Demo d = new Demo();
31         d.show("haha");
32         d.show(new Integer(4));
33         d.print("heihei");
34         */
35         /*
36         Demo<Integer> d = new Demo<Integer>();
37 
38         d.show(new Integer(4));
39         d.print("hah");
40 
41         Demo<String> d1 = new Demo<String>();
42         d1.print("haha");
43         d1.show(5);
44         */
45     }
46 }

5,泛型也可以定义在接口上
用法举例:

 

泛型接口
 1 interface Inter<T>
 2 {
 3     void show(T t);
 4 }
 5 
 6 /*
 7 class InterImpl implements Inter<String>
 8 {
 9     public void show(String t)
10     {
11         System.out.println("show :"+t);
12     }
13 }
14 
15 */
16 
17 class InterImpl<T> implements Inter<T>
18 {
19     public void show(T t)
20     {
21         System.out.println("show :"+t);
22     }
23 }
24 class GenericDemo5 
25 {
26     public static void main(String[] args) 
27     {
28 
29         InterImpl<Integer> i = new InterImpl<Integer>();
30         i.show(4);
31         //InterImpl i = new InterImpl();
32         //i.show("haha");
33     }
34 }

6,泛型的限定

? 通配符。也可以理解为占位符。
泛型的限定;
? extends E: 可以接收E类型或者E的子类型。上限。
? super E: 可以接收E类型或者E的父类型。下限

限定使用示例1
  1 import java.util.*;
  2 
  3 class  GenericDemo6
  4 {
  5     public static void main(String[] args) 
  6     {
  7         /*
  8         ArrayList<String> al = new ArrayList<String>();
  9 
 10         al.add("abc1");
 11         al.add("abc2");
 12         al.add("abc3");
 13 
 14         ArrayList<Integer> al1 = new ArrayList<Integer>();
 15         al1.add(4);
 16         al1.add(7);
 17         al1.add(1);
 18 
 19         printColl(al);
 20         printColl(al1);
 21         */
 22 
 23         ArrayList<Person> al = new ArrayList<Person>();
 24         al.add(new Person("abc1"));
 25         al.add(new Person("abc2"));
 26         al.add(new Person("abc3"));
 27         printColl(al);
 28 
 29         ArrayList<Student1> al1 = new ArrayList<Student1>();
 30         al1.add(new Student1("abc--1"));
 31         al1.add(new Student1("abc--2"));
 32         al1.add(new Student1("abc--3"));
 33         printColl(al1);  //ArrayList<? extends Person> al = new ArrayList<Student>();error
 34         
 35         TreeSet<Student1> ts = new TreeSet<Student1>(new Comp());
 36         ts.add(new Student1("tsabc1"));
 37         ts.add(new Student1("tsabc2"));
 38         ts.add(new Student1("tsabc3"));
 39         
 40         printColl(ts);
 41     }
 42     /**
 43      * 可以接收Person类型或者其子类型
 44      * @param al
 45      */
 46     public static void printColl(Collection<? extends Person> al)
 47     {
 48         Iterator<? extends Person> it = al.iterator();
 49 
 50 
 51         while(it.hasNext())
 52         {
 53             System.out.println(it.next().getName());
 54         }
 55     }
 56     /*
 57     public static void printColl(ArrayList<?> al)//ArrayList al = new ArrayList<Integer>();error
 58     {
 59         Iterator<?> it = al.iterator();
 60 
 61 
 62         while(it.hasNext())
 63         {
 64             System.out.println(it.next().toString());
 65         }
 66     }
 67     */
 68 }
 69 
 70 class Person
 71 {
 72     private String name;
 73     Person(String name)
 74     {
 75         this.name = name;
 76     }
 77     public String getName()
 78     {
 79         return name;
 80     }
 81 }
 82 
 83 class Student1 extends Person
 84 {
 85     Student1(String name)
 86     {
 87         super(name);
 88     }
 89 
 90 }
 91 
 92 
 93 /*
 94 
 95 class Student implements Comparable<Person>//<? super E>
 96 {
 97     public int compareTo(Person s)
 98     {
 99         this.getName()
100     }
101 }
102 */
103 class Comp implements Comparator<Person>
104 {
105     public int compare(Person s1,Person s2)
106     {
107 
108         //Person s1 = new Student("abc1");
109         return s1.getName().compareTo(s2.getName());
110     }
111 }

 

限定使用示例2
 1 import java.util.*;
 2 
 3 class Person
 4 {
 5     private String name;
 6     Person(String name)
 7     {
 8         this.name = name;
 9     }
10     public String getName()
11     {
12         return name;
13     }
14     public String toString()
15     {
16         return "person :"+name;
17     }
18 }
19 
20 class Student extends Person
21 {
22     Student(String name)
23     {
24         super(name);
25     }
26 
27 }
28 
29 class Worker extends Person
30 {
31     Worker(String name)
32     {
33         super(name);
34     }
35 }
36 class GenericDemo7 
37 {
38     public static void main(String[] args) 
39     {
40         
41         TreeSet<Student> ts = new TreeSet<Student>(new Comp());
42 
43         ts.add(new Student("abc03"));
44         ts.add(new Student("abc02"));
45         ts.add(new Student("abc06"));
46         ts.add(new Student("abc01"));
47         
48         Iterator<Student> it = ts.iterator();
49 
50         while(it.hasNext())
51         {
52             System.out.println(it.next().getName());
53         }
54         /**/
55 
56 
57 
58         TreeSet<Worker> ts1 = new TreeSet<Worker>(new Comp());
59 
60         ts1.add(new Worker("wabc--03"));
61         ts1.add(new Worker("wabc--02"));
62         ts1.add(new Worker("wabc--06"));
63         ts1.add(new Worker("wabc--01"));
64 
65 
66         Iterator<Worker> it1 = ts1.iterator();
67 
68         while(it1.hasNext())
69         {
70             System.out.println(it1.next().getName());
71         }
72     }
73 }
74 
75 /*
76 class StuComp implements Comparator<Student>
77 {
78     public int compare(Student s1,Student s2)
79     {
80         return s1.getName().compareTo(s2.getName());
81     }
82 }
83 
84 class WorkerComp implements Comparator<Worker>
85 {
86     public int compare(Worker s1,Worker s2)
87     {
88         return s1.getName().compareTo(s2.getName());
89     }
90 }
91 */
92 //将上面两个比较器可以合并成一个,类型限定为父类型Person,这样可以接收其子类型的对象
93 class Comp implements Comparator<Person>
94 {
95     public int compare(Person p1,Person p2)
96     {
97         return p2.getName().compareTo(p1.getName());
98     }
99 }

 

       --------- android培训java培训期待与您交流 --------详细请查看:http://edu.csdn.net/heima/

posted on 2012-08-03 23:02  doublewinwin  阅读(227)  评论(0编辑  收藏  举报