PriorityQueue<Integer> pq = new PriorityQueue<>(); // first
Queue<Integer> pq = new PriorityQueue<>(); // second
My Question:
Which one is better? I see many examples use first one, however I also heard program against interface. The type of declaration should be as general as possible. PriorityQueue implements Queue interface, therefore from second argument, we should use second one.
PS:
This example is quite different from ArrayList<Integer> list = new ArrayList<>()
vs
List<Integer> list = new ArrayList<>()
, since I never see any production codes use the first one for ArrayList
and we always use the second one. However, I really see many examples use the first one for PriorityQueue
.
You should use an interface general enough to fit your needs and not impose implementation details, but specific enough to fit your exact use case.
If you need some queue without any use of prioritization functionality (e.g. your code does not use any knowledge of prioritization), then use Queue
. That way you can change actual implementation within single line.
If your code uses prioritization features and rely on them, then you definitely should use PriorityQueue
, because Queue
will be too general and will lead to errors when prioritization methods are called.