Java Generics Programming with Collection
I have being stuck with this assignment for weeks now. I just need some help for starting. Here is first requriment:
Design a generic container called GenericOrder that acts as a collection of an arbitrary number of objects in Product开发者_StackOverflow社区s.java. Design a mechanism that gives each instance of the container a unique identifier. Implement as many methods as necessary. You must use Java generics features.
Here is what I have, I don't if I did right or not. The instructor says, this GenericOrder must use collection to hold multiple "Product".
public class GenericOrder<T> {
private T theProduct;
private static int count = 1;
private final int orderNumber = count++;
private Collection<T> genCollection;
public GenericOrder(T theClass)
{
this.theProduct = theClass;
}
public String getProductID()
{
return theProduct.getClass().getName() + ": " + orderNumber;
}
public T createInstance()
throws IllegalAccessException, InstantiationException {
return this.theProduct;
}
}
I would imagine there can be multiple "products" per "order":
public class GenericOrder<T> {
List<T> productsOrdered ...
public GenericOrder(List<T> products) {
...
}
}
But I really have no idea how generics are supposed to help with that, and I can't honestly "piece together" the assignment from just that context so, YMMV.
Happy coding. :)
Design a generic container called GenericOrder that acts as a collection of an arbitrary number of objects
Rather change your container to include what @pst suggested.
Design a mechanism that gives each instance of the container a unique identifier.
Here you got it almost right. But your general thinking was correct.
public class GenericOrder<T> {
private static int ID = 0;
private String serial;
List<T> products;
public GenericOrder() {
serial = "CONTAINER_" + ID++;
products = new ArrayList<T>();
}
public String getUniqueSerial() {
return serial;
}
public void addProduct(T newProduct) {
products.add(newProduct);
}
public int getNumberOfProducts() {
return products.size();
}
}
I might be all wrong here, but it sounds to me like you should inherit from Collection. And for the unique identifier I would perhaps use a map.
精彩评论