I have two questions, actaully... First off, Why cant I do this:
List<Object> object = new List<Object>();
And second, I have a method that returns a List<?>
, how would I turn that into a List<Object>
, would I be able to simply cast it?
Thank you!
In practical terms there is no difference, they both compile down to the exact same code. List<Object> though is showing that you have thought about what will go in the list and know it could be anything, whereas List on its own shows nothing.
In Java, a list interface is an ordered collection of objects in which duplicate values can be stored. Since a List preserves the insertion order, it allows positional access and insertion of elements. List interface is implemented by the following classes: ArrayList. LinkedList.
In category theory, an abstract branch of mathematics, and in its applications to logic and theoretical computer science, a list object is an abstract definition of a list, that is, a finite ordered sequence.
The List interface in Java provides a way to store the ordered collection. It is a child interface of Collection. It is an ordered collection of objects in which duplicate values can be stored. Since List preserves the insertion order, it allows positional access and insertion of elements.
Why cant I do this:
List<Object> object = new List<Object>();
You can't do this because List
is an interface, and interfaces cannot be instantiated. Only (concrete) classes can be. Examples of concrete classes implementing List
include ArrayList
, LinkedList
etc.
Here is how one would create an instance of ArrayList
:
List<Object> object = new ArrayList<Object>();
I have a method that returns a
List<?>
, how would I turn that into aList<Object>
Show us the relevant code and I'll update the answer.
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