Brent R
Brent R

Reputation: 17

How do I add multiple classes to a Generic ArrayList?

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.

Upvotes: 0

Views: 55

Answers (1)

rzwitserloot
rzwitserloot

Reputation: 102953

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.

Upvotes: 1

Related Questions