Declaring a LinkedList in Java

前端 未结 11 1867
北荒
北荒 2021-02-20 14:26

I always learn when we declare a collection we should do, Interface ob = new Class(), if i want to use for example a LinkedList i\'ll do List ob = new LinkedL

相关标签:
11条回答
  • 2021-02-20 14:31

    Not exactly 100% correct.

    A preferred way to declare any collection is to include the data type it's holding. So, for your example, it'd be LinkedList<Integer> ob = new LinkedList<Integer>();.

    0 讨论(0)
  • 2021-02-20 14:32

    Isn't LinkedList ob = new LinkedList() 100% correct?

    Well I'd suggest using the generic form, but sure - if you want to use functionality which is specific to LinkedList, you need to declare the variable accordingly.

    You might want to check whether the Deque<E> or Queue<E> interfaces have what you want though. If they do, use those in-keeping with the idea of describing what you need rather than what implementation you'll use.

    0 讨论(0)
  • 2021-02-20 14:32

    LinkedList is a generic. You should be doing:

    LinkedList<String> linkedList = new LinkedList<String>();
    

    (or whatever else you need to store in there instead of String)

    0 讨论(0)
  • 2021-02-20 14:33

    If you actually have a need to use methods that are not on the List interface, there is certainly nothing wrong with using LinkedList's API. The general rule of programming to the List interface recognizes that 1) it's pretty rare to need those methods, and 2) in most people's experience, it's way more likely that I discover I need to sort the list and/or use a lot of random access, and decide to switch to an ArrayList, than it is I need one of the methods only LinkedList has.

    It may be also that you could be programming to the Queue interface, if you find List isn't giving you what you need.

    0 讨论(0)
  • 2021-02-20 14:38

    Yes,

    LinkedList<...> items = new LinkedList<...>();
    

    is perfectly correct if you know that items will depend on methods of LinkedList<T> that are not captured in the List<T> interface.

    0 讨论(0)
  • 2021-02-20 14:41

    You should always try to keep the declaration at the highest level possible, meaning that you should stop at the highest level that provides all the functionality that you need: if List methods are not enough, you're perfectly fine with your LinkedList declaration.

    0 讨论(0)
提交回复
热议问题