在Collection上调用addFirst

xai*_*ain 0 java collections

Collection col = new LinkedList();
Run Code Online (Sandbox Code Playgroud)

有办法打电话col.addFirst吗?

Boz*_*zho 5

是的,如果你施放到LinkedList:

((LinkedList) col).addFirst(..)
Run Code Online (Sandbox Code Playgroud)

但这是不鼓励的,因为你并不总是知道集合的具体类型.您可以查看instanceof,但这不是好的面向对象的代码.如果你真的需要一个LinkedList,需要一个LinkedList(而不是Collection)