This week's book giveaway is in the Design forum.
We're giving away four copies of Design for the Mind and have Victor S. Yocco on-line!
See this thread for details.
Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Can LinkedList be an object of Collection?

 
Albert Park
Greenhorn
Posts: 28
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,
I am learning about collection framework, and little lost here.
Apologize for my ignorance in advance.
I know we can write,

List<String> list = new LinkedList<String>();

I learned that LinkedList extends AbstractList, and that AbstractList implements List interface.
Since List interface also extends to Collection interface,
Why can't I create,

Collection<String> list = new LinkedList<String>();
and access those methods in LinkedList such as addFirst, addLast etc, without having to cast?

Is it because of some sort of interface rule that Collection interface is not directly related to LinkedList?
 
Jeff Verdegan
Bartender
Posts: 6109
6
Android IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Albert Park wrote:
Why can't I create,

Collection<String> list = new LinkedList<String>();


You can.

and access those methods in LinkedList such as addFirst, addLast etc, without having to cast?


Because list is declared as Collection, and the compiler only cares about what type list is declared as. It doesn't know or care that at runtime it will point to a LinkedList.

It's the same thing as if you do Even though x points to a String, you can't call x.length() or x.charAt(), etc. without casting because all the compiler knows is that x is an Object.

 
Albert Park
Greenhorn
Posts: 28
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
ahh,
Nvm. Got everything wrong.
You can't use those methods when you use List.
Thanks for your help.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic