我有一个关于Java Generics的作业问题。给定的类是Product.java。它有抽象类产品,然后是ComputerPart,Peripheral,Fruit,Cheese和Service extends Product。
设计并实现一个名为OrderProcessor的类。您必须至少实现以下方法:
accept; // this method accepts a GenericOrder or any of its subclass objects and stores it in any internal collection of OrderProcessor.
process; // this method sorts all accepted orders in the internal collection of GenericOrder into collections of ComputerPart, Peripheral, Cheese, Fruit, and Service. You must associate each object with the unique identifier. You may refer to the TwoTuple.java example in the text book.
dispatchXXX; // this method simulates the dispatch of the sorted collections. For example, the method dispatchComputerParts() should produce this output:
Motherboard name=Asus, price=$37.5, order number=123456
Motherboard name=Asus, price=$37.5, order number=987654
RAM name=Kingston, size=512, price=$25.0, order number=123456
You may overload each of the above methods as you think necessary.
创建一个客户端类来测试OrderProcessor。您需要创建一个用于测试目的的datagenerator。这不是强制性的,但您可以在TIJ第637至638页中使用数据生成器的变体。
我已经完成了1条要求,但我很难理解第2条要求。这是我做的代码:
public class GenericOrder<T> {
private static long counter = 1;
private final long id = counter++;
private List<T> products;
private T theClass;
public GenericOrder()
{
products = new ArrayList<T>();
}
public long getId() {
return id;
}
public void addProduct(T newProduct) {
products.add(newProduct);
}
public int getNumberOfProducts() {
return products.size();
}
public List<T> getProducts()
{
return products;
}
public void setProducts(List<T> products)
{
this.products = products;
}
public T get()
{
return theClass;
}
public void set(T theClass)
{
this.theClass = theClass;
}
}
public class ComputerOrder<T> extends GenericOrder<T> {
private List<T> products;
private T theClass;
public ComputerOrder()
{
products = new ArrayList<T>();
}
public void addProduct(T newProduct) {
products.add(newProduct);
}
public int getNumberOfProducts() {
return products.size();
}
public List<T> getProducts()
{
return products;
}
public void setProducts(List<T> products)
{
this.products = products;
}
public T get()
{
return theClass;
}
public void set(T theClass)
{
this.theClass = theClass;
}
}
请在这里帮助我,看看是否有人比我更了解第二个要求。 谢谢大家。
答案 0 :(得分:1)
我认为第二部分正在寻找一个具有上限类型限制的类,所以可能是这样的:
public class ComputerOrder<T extends Product> extends GenericOrder<T> {
// etc...
}
修改强>
我错过了水果和奶酪课程。为了使类型边界起作用,您很可能需要将计算机产品编码到接口并使用以下内容:
public class ComputerOrder<T implements MyInterface> extends GenericOrder<T> {
// etc...
}
有关有界类型参数的更多信息,请阅读here。
答案 1 :(得分:1)
您应该添加的是ComputerParts和Peripherals等常用的方法。
答案 2 :(得分:0)
试试这个:
interface CO{} //for computer orders
interface PTO{} //party tray orders
class ComputerPart implements CO{}
class Peripheral implements CO{}
class Fruits implements PTO{}
class Cheese implements PTO{}
class Service implements CO, PTO{}
public static class ComputerOrders<T extends CO> extends GenericOrder{}
public static class PartyTrayOrder <T extends PTO> extends GenericOrder {}