Java 违反检查泛型对象列表的方法
这是我们的一项任务 任务说明如下: 您需要将实现添加到Violator.defraud()方法,该方法将 请执行以下操作: 根据方法签名创建框列表 将纸张对象至少放在列表中的一个框中,并显示结果列表 如果通过NaiveQualityControl检查,则不应更改方法 签名或更改任何其他类的代码,只需添加实现 欺骗方法Java 违反检查泛型对象列表的方法,java,generics,jvm,type-erasure,Java,Generics,Jvm,Type Erasure,这是我们的一项任务 任务说明如下: 您需要将实现添加到Violator.defraud()方法,该方法将 请执行以下操作: 根据方法签名创建框列表 将纸张对象至少放在列表中的一个框中,并显示结果列表 如果通过NaiveQualityControl检查,则不应更改方法 签名或更改任何其他类的代码,只需添加实现 欺骗方法 /*此类及其子类应通过质量检查*/ 类面包店{} 类蛋糕扩展面包房{} /*但这不应该*/ 课堂论文{} /*这些箱子是用来装东西的*/ 类框{ 作废put(T项){/*实现省略
/*此类及其子类应通过质量检查*/
类面包店{}
类蛋糕扩展面包房{}
/*但这不应该*/
课堂论文{}
/*这些箱子是用来装东西的*/
类框{
作废put(T项){/*实现省略*/}
T get(){/*实现省略了*/}
}
/*这个质量检查员确保出售的盒子里有面包房和其他东西*/
类质量控制{
公共静态布尔检查(List您可以通过使用(通过删除boxList
的泛型)绕过它。事实上,如果您这样做,您可以添加几乎任何类型的对象
:
public-ListHint:它没有说明代码必须在没有关于使用未检查或不安全操作的警告的情况下编译。
/* This class and its subclasses should pass quality check */
class Bakery {}
class Cake extends Bakery {}
/* But this should not */
class Paper {}
/* These boxes are used to pack stuff */
class Box<T> {
void put(T item) { /* implementation omitted */ }
T get() { /* implementation omitted */ }
}
/* This quality checker ensures that boxes for sale contain Bakery and anything else */
class NaiveQualityControl {
public static boolean check(List<Box<? extends Bakery>> boxes) {
/* Method signature guarantees that all illegal
calls will produce compile-time error... or not? */
return true;
}
}
class Violator {
public static List<Box<? extends Bakery>> defraud() {
// Add implementation here
}
}
public static List<Box<? extends Bakery>> defraud() {
List<Box<? extends Bakery>> boxList = new ArrayList<>();
Box<Paper> paperBox = new Box<>();
Box<Bakery> bakeryBox = new Box<>();
Box<Cake> cakeBox = new Box<>();
boxList.add(bakeryBox);
boxList.add(cakeBox);
boxList.add(paperBox); // compile time error, required type <? extends Bakery>
return boxList;
}