1. 程式人生 > >Java泛型總結之一

Java泛型總結之一

oid ring 結果 dem resolv poi error lan 類型轉換

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);}}

Java泛型總結之一