So I have a line of code that goes:
List<Deque<Integer>> pegs = new Arraylist<>();
for(int i=0; i< NUM_PEGS; i++){
pegs.add(new LinkedList<Integer>());
}
I am wondering what extra functionalities does an Arraylist get by implementing the interface List? And is the reason I am able to add a LinkedList to pegs because a LinkedList implements the Deque interface?
-
1Possible duplicate of Java PolymorphismTezra– Tezra2017年08月07日 18:26:12 +00:00Commented Aug 7, 2017 at 18:26
-
Try a google search for "Java API". Read the pages for ArrayList, LinkedList, List, and Deque. The truth is out there.DwB– DwB2017年08月07日 18:27:14 +00:00Commented Aug 7, 2017 at 18:27
-
You can read the java docs to see yes, LinkedList implements Deque. Also, read up about polymorphism and Object-Oriented Programming concepts.Tezra– Tezra2017年08月07日 18:27:45 +00:00Commented Aug 7, 2017 at 18:27
2 Answers 2
I wouldn't say that an ArrayList gets extra functionality by implementing the List interface. It actually provides more functionality over what is specified in the List contract. You can compare the documentation for List and ArrayList to see the differences.
For your second question, yes, you can see in the documentation for Deque that it is implemented by LinkedList, among others.
3 Comments
Normally, a class does not receive any "extra functionalities" by implementing an interface.
(This has changed a bit since java 8, because interfaces can now contain default methods, so it is actually possible to receive extra functionality by implementing an interface, but that's not what this question is about.)
When implementing an interface, a class has to provide all the functionality that the interface requires to be provided. Code must be added to the class to provide that functionality. ArrayList does all that in order to offer the List interface.
So, you might ask, what's the point of implementing an interface?
The point is that then in your code you can refer to the list as simply a List, without knowing that it is actually an ArrayList, which means that your code can then work with any class that implements the List interface, not just with ArrayList.
As for your 2nd question: the answer is "yes".