会不会报错?在多少行?怎么修改?java
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(); } } }
答案ide
//错误在1六、17行,翻译后以下 List<Goods> goods=new ArrayList<Phone>();//这在集合中是不容许的,必须先后泛型保持一致 //修改:将38行改为 public void sellAll(List< ? extends Goods> goods)//意思是goods和它子类均可以
不须要强制转换this
避免了运行时异常翻译
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()); } }
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); } }
或者code
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); } }