Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List<Object> and List<?>

Tags:

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!

like image 696
Christopher Avatar asked Apr 03 '12 06:04

Christopher


People also ask

What is the difference between list <?> And list object?

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.

What list <?> Means in Java?

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.

What means list object?

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.

What is use of list object in Java?

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.


1 Answers

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 a List<Object>

Show us the relevant code and I'll update the answer.

like image 176
NPE Avatar answered Sep 17 '22 01:09

NPE