Java programming to interfaces shall I use it all the time, especially for collections

Akshay Naik :

As suggested almost everywhere shall I be using interface all the time, especially when working with collections.

// Using interfaces
List<Integer> list = new LinkedList<Integer>();
((LinkedList) list).offerFirst(num);

//Using concrete class
LinkedList list = new LinkedList<Integer>();
list.offerFirst(num);

In first approach compiler gives warning and even syntax seems cumbersome.

warning: [unchecked] unchecked call to offerFirst(E) as a member of the raw type LinkedList
Eran :

If you are using the offerFirst method, perhaps you should be programming to the Deque interface (which represents double ended queue) instead of the List interface:

Deque<Integer> deque = new LinkedList<Integer>();
deque.offerFirst(num);

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=111545&siteId=1