一:
注意:数据类型的安全性问题可以理解为避免了数据类型转换错误。
1 package com.example; 2 //?是通配符,object是任意类型,不写类型 3 class A<T>{ 4 private T age; 5 private T name; 6 7 public T getAge() { 8 return age; 9 } 10 11 public void setAge(T age) { 12 this.age = age; 13 } 14 15 public T getName() { 16 return name; 17 } 18 19 public void setName(T name) { 20 this.name = name; 21 } 22 } 23 public class MyClass { 24 public static void main(String[] args){ 25 A<String> a = new A<String>(); 26 a.setAge("100"); 27 a.setName("hello"); 28 System.out.println("name is :"+ a.getName() + ",age is :"+ a.getAge()); 29 } 30 }
二:通配符
三:泛型接口
1 package com.example; 2 interface a<T>{ 3 public abstract void say(T name); 4 } 5 6 class People implements a<String>{ 7 8 int b; 9 10 public int getB() { 11 return b; 12 } 13 14 public void setB(int b) { 15 this.b = b; 16 } 17 18 @Override 19 public void say(String name) { 20 System.out.print(this.getB()+name); 21 22 } 23 } 24 25 public class MyClass { 26 public static void main(String[] args){ 27 People p = new People(); 28 p.b = 10; 29 p.say("hello"); 30 } 31 }
四:泛型方法
1 package com.example; 2 class A { 3 public <T>T tell(T t){ 4 System.out.println(t); 5 return t; 6 }; 7 } 8 public class MyClass { 9 public static void main(String[] args){ 10 A a = new A(); 11 a.tell("hello"); 12 a.tell(12); 13 } 14 }
五:泛型数组
1 package com.example; 2 3 public class MyClass { 4 public static void main(String[] args){ 5 String arr[] = {"i","am","zwzx"}; 6 tell(arr); 7 } 8 public static <T>void tell(T arr[]){ 9 for (int i = 0 ;i <arr.length;i++){ 10 System.out.println(arr[i]); 11 } 12 } 13 }