Why is Queue an interface, but others like Stack and ArrayList are classes?
I understand that interfaces are made so that clients can implement them and add on their own methods, whereas with classes if every client needs their methods in there it will become huge and bloated..
...or am I missing something here?
The java. util. Interfaces contains the collections framework, legacy collection classes, event model, date and time facilities, internationalization, and miscellaneous utility classes (a string tokenizer, a random-number generator, and a bit array).
A class can be inherited by another class using the keyword 'extends'. An Interface can be inherited by a class using the keyword 'implements' and it can be inherited by another interface using the keyword 'extends'. A class can contain constructors. An Interface cannot contain constructors.
Definition. A package is an organized set of related classes and interfaces whereas an interface is a set of fields and abstract methods that mainly allows implementing abstraction. Thus, this is the main difference between package and interface.
A Queue
can be implemented in a number of fashions, as can a List
or a Set
. They all merely specify a contract for different kinds of collections.
An ArrayList
, however, is a particular implementation of a List
, made to internally use an array for storing elements. LinkedList
is also an implementation of a List
, which uses a series of interconnected nodes, i.e. a doubly linked list. Similarly, TreeSet
and HashMap
are particular implementations of sets and maps, respectively.
Now, Stack
is a odd case here, particularly because it is a legacy class from older versions of Java. You really shouldn't use a Stack
anymore; instead, you should use its modern equivalent, the ArrayDeque
. ArrayDeque
is an implementation of a Deque
(a double-ended queue), that internally uses an array for storage (which is just what Stack
does). A Deque
supports all of the operations of a Stack
, like pop
, push
, etc. Other implementations of Deque
include LinkedList
, as mentioned by someone else, although this deviates from Stack
in that underlying it is not an array, but a doubly-linked list :-p
Now, there are plenty of implementations of Queue
, and many different types of Queue
s. You not only have BlockingQueue
s (often used for producer-consumer), whose common implementations include LinkedBlockingQueue
and ArrayBlockingQueue
, but also TransferQueue
s, and so on. I digress... you can read more on the collections API in the relevant Java Tutorial.
You get the idea of interfaces correctly. In this case Java standard library already provides both implementations and interfaces. You are better of using an interface so you can switch the implementation any time.
Hope it makes sense.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With