0

ArrayList of custom class has no .add() method:

I can define an ArrayList of Object's:

ArrayList<Object> thing = new ArrayList<Object>();


thing.add(otherThing); // works

However, when I define a list of a custom class Thing:

ArrayList<Thing> thing = new ArrayList<Thing>();


thing.add(otherThing); // error


Canvas.java:33: cannot find symbol
symbol  : method add(java.lang.Object)
location: class java.util.ArrayList<Thing>
            thing.add(otherThing);
                   ^
1 error

Is this possible?

Thanks

1
  • 1
    How is otherThing declared? Commented Apr 23, 2013 at 3:39

3 Answers 3

7

Your otherThing must be of the type Thing. Currently its of the type Object, and that's why it worked for the first case, but failed in the second case.

In your first case, the ArrayList<Object> takes elements of type Object. Since the otherThing is of the type Object too, and so it works.

In the second case, the ArrayList<Thing> takes elements of type Thing. Since, your otherThing is still of the type Object, whereas it should have been of the type Thing, you get that error.

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

Comments

0
ArrayList<Thing> thing = new ArrayList<Thing>(); 

For this you can only add types of/instances of Thing only other than that is not allowed as its violates Java Generic guideline.

ArrayList<Object> thing = new ArrayList<Object>();  

as here you are specifiying Object and as Object is super class it will work fine.

Comments

0

otherThing is not declared as Thing but an Object.

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.