What is the difference between List
and List<Object>
in java?
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> .
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.
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.
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.
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.
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