Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Java Java Data Structures Efficiency! Menu UI

Konstantinos Pedarakis
Konstantinos Pedarakis
21,301 Points

addSong method vs add method of List

hi in this example in the line 47, if i wanted to use the add method of the ArrayList why im getting an error? typing something like that

songBook.add(song);

instead of:

songBook.addSong(song);

it is supposed that SongBook is an ArrayList as we defined in the Contructor of SongBook class, so i can't understand why im getting an error on this. any clarifications would be appreciate.

Thanks

1 Answer

andren
andren
28,524 Points

SongBook is not a list, at no point is it defined as such, in the constructor of SongBook you set mSong (which is a private member variable within SongBook) to be a new ArrayList, but that does not make SongBook itself an ArrayList.

That is why the addSong method is needed in the first place, so that you can add things to the mSong list.

It's no different from having a class with String or int member variables, setting those variables in the Class's constructor would not make the Class a String or an int, the same applies to Lists.

Konstantinos Pedarakis
Konstantinos Pedarakis
21,301 Points

andren Thanks for the clarification. Now i got it 100%. i don't know i was confused so much with that. i shouldn't! anyway thank you very much.