Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List and List<?> in Java

Tags:

java

What is the difference between List and List<?>? I know I can't add any element to the List<?>. I have a code:

List<String> myList = new ArrayList<String>();
processList(myList);
processListGeneric(myList);

public static void processList(List myList) {
Iterator it = myList.iterator();
while(it.hasNext())
    System.out.println(it.next());
}

public static void processListGeneric(List<?> myList) {
    Iterator<?> it = myList.iterator();
    while(it.hasNext())
        System.out.println(it.next());
}

The name of the two methods cannot be the same, because it causes compile time error. So is there any difference in these two approaches?

like image 576
raki Avatar asked Jun 04 '13 10:06

raki


People also ask

What is the difference between list <?> And List object in Java?

The difference to List now is that List is untyped and therefore no type checks at all are performed, which ultimately leads to certain warnings and can lead to weird runtime behavior. While Java knows that List<Object> is a list that might contain anything, it doesn't know that about a List .

What Does list <?> Mean 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.

Can we use list <?> In Java?

List in Java provides the facility to maintain the ordered collection. It contains the index-based methods to insert, update, delete and search the elements. It can have the duplicate elements also. We can also store the null elements in the list.


1 Answers

Both do the same, but in second case compiler is informed that you really want a list with no type bounds and raises no warnings. If you are working with Java 5 or later you are encouraged to use second approach.

like image 145
Grzegorz Żur Avatar answered Sep 30 '22 17:09

Grzegorz Żur