泛型方法,通配符使用,有界类型参数
- 泛型方法:带类型参数的方法,可以为静态和非静态
- 类的成员方法和构造方法都可以定义为泛型方法
- 类型参数的作用域仅限于声明的方法和构造方法
- 泛型方法必须在方法返回值前指定泛型
interface Entry<K,V>{
public K getKey() ;
public V getValue();
}
class Pair <K,V> implements Entry<K,V>{
private K key ;
private V value ;
public Pair(){}
public Pair(K key, V value){
this.key = key ;
this.value = value ;
}
public void setKey(K key){
this.key = key ;
}
public void setValue(V value){
this.value = value ;
}
@Override
public K getKey() {
return key;
}
@Override
public V getValue() {
return value;
}
}
public class Util {
public static <T> void swap(T [] array, int i, int j){
T temp = array[i] ;
array[i] = array[j] ;
array[j] = temp ;
}
public static <K,V> boolean compareTo(Pair<K,V> p1 , Pair<K,V> p2){
return p1.getKey().equals(p2.getKey()) && p1.getValue().equals(p2.getValue()) ;
}
public static void main(String[] args){
Integer [] array = new Integer[]{1,2,3,4} ;
swap(array,0,3);
for(Integer m : array){
System.out.print(m + " ") ;
}
Pair <Integer, String> p1 = new Pair<>(1,"one") ;
Pair <Integer, String> p2 = new Pair<>(2,"two") ;
System.out.println(compareTo(p1,p2)) ;
}
}
- 通配符的使用,问号?就是通配符,表示方法可接受元素是任何类型的对象
- 当需要传递的对象类型不确定时,可以使用通配符
import java.util.ArrayList;
import java.util.List;
public class WildCardDemo {
public static void printList(List<?> list){
for(Object m : list){
System.out.print(m + " ") ;
}
}
public static void main(String[] args){
List <Integer> list = new ArrayList<>() ;
list.add(new Integer(1)) ;
list.add(new Integer(2)) ;
list.add(new Integer(3)) ;
printList(list);
List <String> myList = new ArrayList<>();
myList.add("dog") ;
myList.add("cat") ;
myList.add("rabbit") ;
printList(myList) ;
}
}
- 有界类型参数
- 限制传递类型参数的类型种类
- 有界类型分为有上界和有下界:
- 上界:? extends 上界类型
- 下界:? super 下届类型
import java.util.ArrayList;
import java.util.List;
public class BoundedTypeDemo {
public static double getAverage(List<? extends Number> numberList){
double total = 0.0 ;
for(Number number : numberList){
total += number.doubleValue() ;
}
return total / numberList.size() ;
}
public static void main(String[] args){
List <Integer> integerList = new ArrayList<>() ;
integerList.add(3) ;
integerList.add(30) ;
integerList.add(300) ;
System.out.println(getAverage(integerList)) ;
List <Double> doubleList = new ArrayList<>() ;
doubleList.add(5.5) ;
doubleList.add(55.5) ;
System.out.println(getAverage(doubleList)) ;
}
}