0

I want to add the add different arrayLists of type Product to orderProcessor. These different arrayLists have objects of type Products and its subclass. Is this code good or are there errors?

for(int i = 0; i < genericOrder.size(); i++) {
    orderProcessor.add(genericOrder.get(I));
    System.out.println(orderProcessor.get(i));
}

Also, later I categorically add these to different arrayLists of different Types. However these types are still subTypes of Product such as ComputerPart object. I am doing this to have different types in different Lists. I don't think it's working since I am not getting any output. What is causing my error?

for (int i = 1; i < orderProcessor.size(); i++){
    computerPart.add((ComputerPart) orderProcessor.get(I)); 
}
2
  • orderProcessor.addAll(genericOrder)? Commented Nov 23, 2014 at 2:51
  • i have tried that. That does not seem to be making a difference. Is there a difference though ? i was scared that while adding like you did, i might be overwriting them. Though it is the second part of my question i am really unclear about @MadProgrammer Commented Nov 23, 2014 at 2:52

2 Answers 2

1

In your second for loop you have:

for (int i = 1; i < orderProcessor.size(); i++){
computerPart.add((ComputerPart) orderProcessor.get(I)); 
}

If orderProcessor only had 1 order in it, then it would never get added to your coumputerPart arrayList because i would not be less than orderProcessor.size(). You can also check the types of your sub classes to add them into the correct ArrayList. Like this (with the int i = 0 fix):

for (int i = 0; i < orderProcessor.size(); i++){
    if (orderProcessor.elementAt(i) instanceof ComputerPart)
        computerPart.add((ComputerPart) orderProcessor.get(I)); 
}

*(I would've commented on this, but I don't have enough rep points...)

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

1 Comment

Hahahah amateur mistake . Corrected !
0
    for (int i=0 ; i< orderProcessor.size();i++){
        if(orderProcessor.get(i) instanceof ComputerPart )
        computerPart.add( orderProcessor.get(i));
        else;
    }

i think the above should work for what i was trying to do ?

Comments

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.