I'm doing an assignment where I can only add specific classes to a generic ArrayList, but the ArrayList does not seem to be adding the classes as intended.
public class ComputerOrder<T extends Product> extends GenericOrder<T> {
private List<T> products;//the list of items
public void addProduct(T t) {
if (t.getClass().isInstance(ComputerPart.class)) {
products.add(t);
}
if (t.getClass().isInstance(Service.class)) {
products.add(t);
}
if (t.getClass().isInstance(Peripheral.class)) {
products.add(t);
}
else System.out.println("Not the right type of object.");
}
Main args test:
public static void main(String[] args) {
ComputerPart c;
c = new ComputerPart(12);
ComputerOrder<Product> g3 = new ComputerOrder<>();
g3.addProduct(c);
g3.print();
}
The expected result would be that ArrayList g3 would be able to add c, since it's an instance of a ComputerPart object, but instead the ArrayList is empty. Could someone explain what I am doing wrong with my code?
Note: that "else" statement is only in there for testing purposes, and seems to indicate that the if statements are not working correctly, since it keeps getting triggered when I test.
else iffor the Service and Peripheral checks. But that won't solve the main problem. Try adding printlns in each conditional clause to help figure out what's going on.isInstancefixed, this is a terrible way to work with generics or object-oriented programming in general.