泛型
思考
會不會報錯?在多少行?怎麼修改?
import javax.swing.*;
import java.util.ArrayList;
import java.util.List;
public class Test {
public static void main(String[] args) {
List<Phone> phoneList = new ArrayList<>();
phoneList.add(new Phone());
phoneList.add(new Phone());
List<Water> waterList = new ArrayList<>();
waterList.add(new Water());
waterList.add(new Water());
SellGoods sellGoods=new SellGoods();
sellGoods.sellAll(phoneList);
sellGoods.sellAll(waterList);
}
}
abstract class Goods{
public abstract void sell();
}
class Phone extends Goods{
@Override
public void sell() {
System.out.println("賣手機");
}
}
class Water extends Goods{
@Override
public void sell() {
System.out.println("賣水");
}
}
class SellGoods{
public void sellAll(List<Goods> goods){
for (Goods g:goods){
g.sell();
}
}
}
答案
//錯誤在16、17行,翻譯後如下
List<Goods> goods=new ArrayList<Phone>();//這在集合中是不允許的,必須前後泛型保持一致
//修改:將38行改成
public void sellAll(List< ? extends Goods> goods)//意思是goods和它子類都可以
泛型的好處
-
不需要強制轉換
-
避免了執行時異常
自定義泛型類
形式一:一個引數
public class customizeGeneric<T> {
private T name;
public T getName() {
return name;
}
public void setName(T name) {
this.name = name;
}
public static void main(String[] args) {
customizeGeneric<String> cg=new customizeGeneric<>();
cg.setName("han");
System.out.println( cg.getName());
}
}
形式二:多個引數(2個及以上)
public class customizeGeneric<T,X> {
private T name;
private X age;
public customizeGeneric(T name, X age) {
this.name = name;
this.age = age;
}
public T getName() {
return name;
}
public void setName(T name) {
this.name = name;
}
public X getAge() {
return age;
}
public void setAge(X age) {
this.age = age;
}
public static void main(String[] args) {
customizeGeneric<String,Integer> cg=new customizeGeneric<>("han",21);
System.out.println(cg.getName()+" "+cg.getAge());
}
}
自定義泛型方法
public class GenericMethod<T> {
public void printValue(T t){
System.out.println(t);
}
public static void main(String[] args) {
GenericMethod gm=new GenericMethod();
gm.printValue(16);
}
}
或者
public class GenericMethod {
public<T> void printValue(T t){
System.out.println(t);
}
public static void main(String[] args) {
GenericMethod gm=new GenericMethod();
gm.printValue(16);
}
}