This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes Can LinkedList be an object of Collection? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Can LinkedList be an object of Collection?" Watch "Can LinkedList be an object of Collection?" New topic
Author

Can LinkedList be an object of Collection?

Albert Park
Greenhorn

Joined: Feb 01, 2012
Posts: 28
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

Joined: Jan 03, 2004
Posts: 6109
    
    6

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

Joined: Feb 01, 2012
Posts: 28
ahh,
Nvm. Got everything wrong.
You can't use those methods when you use List.
Thanks for your help.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Can LinkedList be an object of Collection?
 
Similar Threads
ArrayLists Imp
Interfaces
Cast LinkedList to ArrayList, enjoy the class cast exception
Collection
Multiple implements same interface