0

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.

2
  • The println will be triggered too often since you haven't used else if for 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. Commented May 25, 2019 at 21:01
  • Even with the isInstance fixed, this is a terrible way to work with generics or object-oriented programming in general. Commented May 25, 2019 at 21:05

1 Answer 1

1

Your primary problem is that you've messed up your isinstance check. That method works in reverse; what you're looking for is:

ComputerPart.class.isInstance(t), not t.getClass().isInstance(ComputerPart.class). But, you can write this a lot more simply as: t instanceof ComputerPart.

Secondarily you've messed up the sysout. Presumably you meant for each 'if' in your code to be an 'else if' instead, except for the first one of course.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks very much, rzwitserloot, the t instanceof ... works. I appreciate the help!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.