Java泛型总结之一

1、使用泛型,有利于降低代码的耦合;

2、泛型可以解决数据类型的安全问题,可以有效避免类型转换异常(ClassCastException)的发生,使程序操作更加安全;

3、

 1 class Point<T>{
 2     private T x;
 3     private T y;
 4     public T getX() {
 5         return x;
 6     }
 7     public void setX(T x) {
 8         this.x = x;
 9     }
10     public T getY() {
11         return y;
12     }
13     public void setY(T y) {
14         this.y = y;
15     }
16 }

4、

 1 public class GenericsPoint {
 2 
 3     public static void main(String[] args) {
 4         Point<Integer> p = new Point<Integer>();
 5         
 6         p.setX(10);
 7         p.setY(20);
 8         int x = p.getX();
 9         int y = p.getY();
10         System.out.println(x);
11         System.out.println(y);
12     }
13 }

输出结果为:

10

20

 

5、

 1 public class GenericsPoint {
 2 
 3     public static void main(String[] args) {
 4         Point<Integer> p = new Point<Integer>();
 5         
 6         p.setX(10);
 7         p.setY("二十");
 8         int x = p.getX();
 9         int y = p.getY();
10         System.out.println(x);
11         System.out.println(y);
12     }
13 }

出现异常:

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 

The method setY(Integer) in the type Point<Integer> is not applicable for the arguments (String)

 

6、指定多个泛型

 1 class Notepad<K,V>{
 2     private K key;
 3     private V value;
 4     public K getKey() {
 5         return key;
 6     }
 7     public void setKey(K key) {
 8         this.key = key;
 9     }
10     public V getValue() {
11         return value;
12     }
13     public void setValue(V value) {
14         this.value = value;
15     }
16 }
17 public class GenericsDemo09 {
18 
19     public static void main(String[] args) {
20         Notepad<String,Integer> t = new Notepad<String,Integer>();
21         t.setKey("zhangsan");
22         t.setValue(30);
23         System.out.println(t.getKey());
24         System.out.println(t.getValue());
25     }
26 }

输出结果为:

zhangsan

30

 

public class GenericsPoint {
public static void main(String[] args) {Point<Integer> p = new Point<Integer>();p.setX(10);p.setY(20);int x = p.getX();int y = p.getY();System.out.println(x);System.out.println(y);}}

posted @ 2017-08-01 08:51  XuGuobao  阅读(146)  评论(0编辑  收藏  举报