Is the collection better than LinkedList?

Collection list = new LinkedList(); // Good?
LinkedList list = new LinkedList(); // Bad?

The first option gives you more flexibility, but is that all? Are there any other reasons to prefer this? What about performance?

+5
source share
6 answers

These are design decisions, and one size is usually not suitable for everyone. Also, the choice of what is used internally for a member variable may (and usually should) differ from what is available to the outside world.

, Java , , . , , RandomAccess, Collection get(index) API. , .

, , ( ) . , , , , Collection List , . , List LinkedList, , .

API-, API-, , , ; add(...) iterator().

+7
Collection list = new LinkedList(); //bad

, , HashSet ( HashSet Collection, ).

LinkedList list = new LinkedList(); //bad?

, .

List list = new LinkedList();//good

, 2 . ( )

+2

. , , .

+2

. , , java List, API, LinkedList, , API. , , API.

+1

. , , LinkedList, .

0

, ( , ). , .

In your example, I would usually declare it as Listsoon as the methods available in Collectionare not very powerful, and the difference between the Listother Collection( Map, Setetc.) is often logically significant.

Also, in Java 1.5+, do not use raw types - if you do not know the type that your list will contain, at least use it List<?>.

0
source

All Articles