1

So I found that Collection as an Interface has many sub-interfaces, and sub-Classes. One thing that is commonly seen is to use the interface instead of using the actual class, which allows flexibility:

List<Interger> L1 = new ArrayList<>();

But this also limits the use of some special methods in the actual Class, (in the case of ArrayList, not so many special methods). But this can be solved by using casting.

List<Integer> L2 = ((ArrayList<Integer>) L1).clone();

However, it is interesting that LinkedList is implementing Collection, List, Queue, Deque.

So what is the best scenario of using LinkedList in common?

List<> L1 = new LinkedList<>();
Queue<> Q1 = new LinkedList<>();
Deque<> D1 = new LinkedList<>();
  1. If I use List, well then it seems unnecessary because I can make List from ArrayList.
  2. Should I always choose the Interface that is just 1 level above the Class, in this case, Deque over Queue?

I guess it is just confusing because Queue and Deque does not implement List, but LinkedList does. And I don't see why should it be?

Thanks,

jxie0755
  • 1,682
  • 1
  • 16
  • 35
  • There is no "best" thing to use here. What kind of functionality do you need to use? Do you need those functionalities defined in `List` or `Queue` or `Deque`? – Sweeper Mar 14 '19 at 17:17
  • 2
    Because you can have implementations of `Queue` and `Deque` that are not Lists -- e.g., `PriorityQueue`. – Andy Thomas Mar 14 '19 at 17:21
  • 1
    You should choose a declared type that serves *all* your requirements for the object. Typically, the most general type that does. If you have to downcast then you've chosen wrongly (and any flexibility you thought you were gaining from the more general type is in that case illusory). – John Bollinger Mar 14 '19 at 17:23
  • @JohnBollinger Thanks! Always avoid downcasting! – jxie0755 Mar 14 '19 at 17:37

1 Answers1

1

According to dependency inversion principle components should depends on abstractions. So, first you need to choose the abstration which best meets your needs (e.g. interface or abstract class). And after that choose concrete implementation.

There is no the best solution for all cases.

ilinykhma
  • 980
  • 1
  • 8
  • 14