List<Object> and List<?>

20

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!

This question is tagged with java list object arraylist

~ Asked on 2012-04-03 06:32:35

The Best Answer is


40

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.

~ Answered on 2012-04-03 06:34:45


6

List<Object> object = new List<Object>();

You cannot do this because List is an interface and you cannot create object of any interface or in other word you cannot instantiate any interface. Moreover, you can assign any object of class which implements List to its reference variable. For example you can do this:

list<Object> object = new ArrayList<Object>();

Here ArrayList is a class which implements List, you can use any class which implements List.

~ Answered on 2012-04-03 06:34:00


Most Viewed Questions: