Java泛型应用总结

一、泛型的引入原因

  在操作集合的时候,之前方法的定义都是Object类型,向集合中添加对象,都自动向上转型,加入的元素可以是任何类型

但是,在取出元素的时候,通常想要使用对象的特有功能,就必须向下转型,此时就可能出现类型转换异常,存在安全隐患。

在JDK1.5时候提出一个解决方案:泛型。

二、泛型的定义及好处

  泛型:是一种应用在编译时期的安全机制,具体的做法:有点类似于数组的思想,定义操作的时候,指定好要操作的类型信息

eg:ArrayList<String>:表示该ArrayList只能操作字符串类型的元素,假如要向其中添加Integer类型,就会编译失败。

<>尖括号中指定被操纵的对象的类型。

  好处:将运行期间可能出现的异常,转化为编译时期的强制检验,避免了强制类型转换;也提供了设计上的便捷

三、泛型的擦除和补偿

  泛型擦除:具体指的是编译器在堆源代码进行完类型检查后,在生成字节码文件的时候,会滤过泛型指定的类型信息,所以

生成的字节码文件中不含有具体的类型信息--变为Object或某个范围,使用泛型擦除主要的目的:其实为了兼容性,为了继续使用

Classloader加载类,同时还要满足以前没有泛型类的加载,所以就在检查完类型匹配后,将泛型类型的信息擦除。

  泛型补偿:当要本来具有泛型的方法在被调用的时候,根据实际类型的Class对象获取类型信息,自动的添加到原来的地方。

 1 import java.util.Iterator;
 2 import java.util.TreeSet;
 3 
 4 /*泛型的简单使用
 5  * */
 6 public class GenericsDemo {
 7 
 8     public static void main(String[] args) {
 9         //TreeSet在添加元素的时候排序,元素必须能够被比较/或传给TreeSet一个比较器
10         TreeSet<Unicorn> t = new TreeSet<Unicorn>();
11         t.add(new Unicorn(2,"huahua"));
12         t.add(new Unicorn(1,"tete"));
13         t.add(new Unicorn(1,"meme"));
14         //遍历集合
15         Iterator<Unicorn> it = t.iterator();
16         while(it.hasNext()){
17             Unicorn u = it.next();
18             System.out.println(u.getAge() + " " + u.getName());
19         }
20     }
21 }
22 
23 class Unicorn implements Comparable<Unicorn>{
24     private int age;
25     private String name;
26     
27     public Unicorn(int age, String name) {
28         this.age = age;
29         this.name = name;
30     }
31 
32     public int getAge() {
33         return age;
34     }
35 
36     public void setAge(int age) {
37         this.age = age;
38     }
39 
40     public String getName() {
41         return name;
42     }
43 
44     public void setName(String name) {
45         this.name = name;
46     }
47 
48     @Override
49     public int compareTo(Unicorn u) {
50         int temp = this.age - u.age;
51         return temp == 0 ? this.name.compareTo(u.name):temp;
52     }
53 }

四、泛型的不同的使用场景

  1.泛型类或接口:表示该类或接口以后要操作的引用类型不确定,所以在定义的时候需要定义为泛型类或接口。

在创建对象的时候,指定具体要操作的类型。类/接口<参数类型>

  2.泛型方法:表示该方法以后要操作的引用类型不确定,所以在定义的时候定义为泛型方法,注意:泛型方法的

定义与其所在的类或接口是否为泛型类或接口没有关系。静态方法由于不能访问泛型类的类型参数,所以假如该静态

方法需要使用泛型,则将该方法定义为泛型方法。泛型方法的调用与普通方法没有区别。<参数类型> 返回值

五、泛型的高级应用

  1.泛型通配符:?表示,通常用于操作任意参数类型的泛型。强调的是通用性。

  2.泛型的界限:其目的是在一定范围内扩大可以操作的参数类型。分为上界限,和下界限。

  泛型上界:表现形式:<? extends A> 表示的含义是:可以操作的参数类型可以是,A类型以及A的子类。通常这种

在集合中取出元素的时候常常使用,通常用A类型来接收取出的元素。<=A

  泛型下界:表现形式:<? super A> 表示的含义是:可以操作的参数类型是:A类型及其父类型。通常这种在接收元素

做比较的时候使用,可以使用自己的比较器,也可以使用父类的比较器。泛型下限的使用不多 。>=A

注意:ArrayList<Animal> list = new ArrayList<Cat>(); 这是错误的两边的泛型类型不匹配。

   ArrayList<? extends Animal> list = new ArrayList<Cat>(); 这样才是正确的写法,泛型匹配。

 1 /*定义泛型类,泛型接口,泛型方法
 2  *注意:既然使用泛型,就表示操作的类型不确定,通常可以调用的
 3  *方法都是公共的方法,从Object里继承得到的方法。
 4  * */
 5 public class Tool<T> {
 6     private T t;
 7     
 8     public T getT() {
 9         return t;
10     }
11 
12     public void setT(T t) {
13         this.t = t;
14     }
15 
16     public void print(T t){
17         System.out.println("print " + t.toString());
18     }
19     public static <Y> void method(Y y){
20         System.out.println("method " + y.toString());
21     }
22 }
 1 /*泛型接口:要么在具体类实现的时候定义参数类型或在创建子类对象的时候明确参数类型
 2  *这是根据什么时候可以明确操作的类型确定的。
 3  * */
 4 public interface GenericsInter<T> {
 5     void method(T t);
 6 }
 7 
 8 class A implements GenericsInter<String>{
 9     @Override
10     public void method(String t) {
11         // TODO Auto-generated method stub
12         
13     }
14 }
15 
16 class B<T> implements GenericsInter<T>{
17     @Override
18     public void method(T t) {
19         // TODO Auto-generated method stub
20         
21     }
22 }
 1 import java.util.*;
 2 
 3 /*使用泛型的通配符,泛型上界限*/
 4 public class GenericsBound {
 5     public static void main(String[] args) {
 6         ArrayList<Personn> list1 = new ArrayList<Personn>();
 7         list1.add(new Personn(23, "hehe"));
 8         list1.add(new Personn(34, "nini"));
 9         ArrayList<Student> list2 = new ArrayList<Student>();
10         list2.add(new Student(13,"keke"));
11         list2.add(new Student(19,"oo"));
12         ArrayList<Integer> list3 = new ArrayList<Integer>();
13         list3.add(9);
14         list3.add(4);
15         printCollection(list1);
16         printCollection(list2);
17         printCollection(list3);
18         printCollection1(list1);
19         printCollection1(list2);
20         //printCollection1(list3);---限定了所以不可以传入该参数
21     }
22     
23     //使用的泛型通配符可以操作泛型参数类型是任意的
24     public static void printCollection(Collection<?> c){
25         Iterator<?> it = c.iterator();
26         while(it.hasNext()){
27             System.out.println(it.next().toString());
28         }
29     }
30     //只接收泛型参数类型是Personn及其子类的集合
31     public static void printCollection1(Collection<? extends Personn> c){
32         Iterator<? extends Personn> it = c.iterator();
33         while(it.hasNext()){
34             System.out.println(it.next().toString());
35         }
36     }
37 
38 }
39 
40 class Personn{
41     private int age;
42     private String name;
43     
44     public Personn(int age, String name) {
45         this.age = age;
46         this.name = name;
47     }
48     public int getAge() {
49         return age;
50     }
51     public void setAge(int age) {
52         this.age = age;
53     }
54     public String getName() {
55         return name;
56     }
57     public void setName(String name) {
58         this.name = name;
59     }
60     
61     public String toString(){
62         return "person " + getName() + " " + getAge();
63     }
64     
65 }
66 
67 class Student extends Personn{
68 
69     public Student(int age, String name) {
70         super(age, name);
71     }
72     public String toString(){
73         return "student " + getName() + " " + getAge();
74     }
75 }
76 
77 class Worker extends Personn {
78 
79     public Worker(int age, String name) {
80         super(age, name);
81     }
82     
83     public String toString(){
84         return "worker " + getName() + " " + getAge();
85     }
86 }
1 public static void printCollection3(Collection<? super Student> c){
2         Iterator<? super Student> it = c.iterator();
3         while(it.hasNext()){
4             System.out.println(it.next().toString());
5         }
6}
泛型下界限:此时只能打印参数类型为Student类型及其父类类型的集合
 1 import java.util.Comparator;
 2 import java.util.TreeSet;
 3 /*泛型下界限的使用
 4  *TreeSet(Comparator<? super E>) 对于元素E类型可以使用自己的比较器或者父类的比较器*/
 5 public class Generic_LowBound {
 6     public static void main(String[] args) {
 7         TreeSet<Student> t1 = new TreeSet<Student>(new ComparateByPersonn());
 8         t1.add(new Student(12,"hyhy"));
 9         t1.add(new Student(14,"uiui"));
10         System.out.println(t1);
11         TreeSet<Student> t2 = new TreeSet<Student>(new ComparateByStudent());
12         t2.add(new Student(12,"hyhy"));
13         t2.add(new Student(14,"uiui"));
14         System.out.println(t2);
15     }
16 }
17 
18 class ComparateByPersonn implements Comparator<Personn>{
19     @Override
20     public int compare(Personn o1, Personn o2) {
21         int temp = o1.getName().compareTo(o2.getName());
22         return temp == 0 ? (o1.getAge() -o2.getAge()) :temp;
23     }
24 }
25 
26 class ComparateByStudent implements Comparator<Student>{
27     @Override
28     public int compare(Student o1, Student o2) {
29         int temp = o1.getName().compareTo(o2.getName());
30         return temp == 0 ? (o1.getAge() -o2.getAge()) :temp;
31     }
32 }
33 
34 class ComparateByWorker implements Comparator<Worker>{
35     public int compare(Worker o1, Worker o2) {
36         int temp = o1.getName().compareTo(o2.getName());
37         return temp == 0 ? (o1.getAge() -o2.getAge()) :temp;
38     }
39 }

 

  

posted @ 2017-11-15 10:51  sun1993  阅读(2429)  评论(0编辑  收藏  举报