会不会报错?在多少行?怎么修改?
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());
}
}
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);
}
}
原文:https://www.cnblogs.com/gxh299988/p/14403032.html