Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java difference between List and List<Object>

Tags:

java

generics

What is the difference between List and List<Object> in java?

like image 603
Rnet Avatar asked Oct 25 '11 07:10

Rnet


People also ask

What is the difference between List and list object?

List is a raw type and thus can contain an object of any type whereas List<T> may contain an object of type T or subtype of T. We can assign a list object of any type to a raw type List reference variable, whereas we can only assign a list object of type <T> to a reference variable of type List<T> .

What is a list object in Java?

List 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. List Interface is implemented by ArrayList, LinkedList, Vector and Stack classes.

Is List also a object in Java?

Since List is an interface, objects cannot be created of the type list. We always need a class that implements this List in order to create an object. And also, after the introduction of Generics in Java 1.5, it is possible to restrict the type of object that can be stored in the List.

What do you mean by 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.


1 Answers

Suppose you've got two lists:

List<Object> mainList = new ArrayList<Object>();

and one with a raw type:

List rawList = new ArrayList();

Now let's do something like this:

List<Integer> intList = new ArrayList<Integer>();
intList.add(42);
mainList.addAll(intList);
rawList.addAll(intList);

But there is somewhere one more list which contains String objects:

List<String> strList = new ArrayList<String>().

When we try to call

strList.addAll(mainList)

we get a Compilation Error :

The method addAll(Collection<? extends String>) in the type List<String> is not applicable for the arguments (List<Object>).

But if we try to call

strList.addAll(rawList)

we get just a warning.

So if you are using only lists of objects in your application it's really no difference between List and List. But since Java 1.5 it's a good idea to use generics for providing compile-time type safety for your application.

like image 95
amukhachov Avatar answered Oct 09 '22 07:10

amukhachov