Call addFirst on a Collection
Collection col = 开发者_StackOverflow中文版new LinkedList();
Is there a way to call col.addFirst
?
Yes, if you cast to LinkedList
:
((LinkedList) col).addFirst(..)
But this is discouraged, because you don't always know the concrete type of the collection. You can check with instanceof
, but that is not good object oriented code. If you really require a LinkedList
, require a LinkedList
(rather than Collection
)
If you declare a variable as Collection, this means that you normally plan to consider this variable, in the rest of your program, as a simple Collection, and not as a linked list. The methods offered by the Collection interface should be sufficient for the rest of your program using this variable.
If you need access to a specific method only present in the LinkedList class, then the variable should be a declared as LinkedList.
I am not sure why you need to use Collection in this case, however you can still "program to an interface and not to an implementation" if you use the interface java.util.Deque which, by chance, also extends java.util.Collection
Deque<String> deque = new LinkedList<String>();
deque.addFirst("Hello");
Collection<String> collection = deque;
If you use List instead of Collection, then the .add() method is available. Add at index 0 to put it in on the first position.
list.add(0, object)
精彩评论