This discussion is archived
2 Replies Latest reply: Mar 28, 2010 10:49 AM by 843793 RSS

List<?> a= new LinkedList<?>();

843793 Newbie
Currently Being Moderated
import java.util.*;
public class Test1 {
     public static void main (String as[]){

          List<?> a= new LinkedList<?>();
          a.add("sd");
          a.add(1);
          a.add(new Integer(3));
          a.add(new Object());

          Iterator itr =a.iterator();
          while(itr.hasNext()){
          System.out.println(itr.next());
          }
          Object[] b= a.toArray();
          for(Object o :b){
               System.out.println(o.toString());     
          }

     }
}

I have a question the above code works if the parameterised type is <Object> or without <> , but when i use <?> it results in Error
Exception in thread "main" java.lang.Error: Unresolved compilation problems:

*     Cannot instantiate the type LinkedList<?>*

so where can i use this <?> and what it exactly mean ??

Thanks in advance
  • 1. Re: List<?> a= new LinkedList<?>();
    843793 Newbie
    Currently Being Moderated
    "<?>" is used to define a wildcard type.

    It is used when referring to types with generic type arguments where you don't know (or don't care) what the actual type argument is.

    That's not very useful when creating objects, because you can always define something here. It's only useful when you get such an object from somewhere else.

    Removing the <> altogether makes it a raw type that is only supported for backwards compatibility with pre-generics legacy code.

    (By the way, please use code tags when posting code in the future. Simply select your code and push the "CODE" button just above the text area).
  • 2. Re: List<?> a= new LinkedList<?>();
    843793 Newbie
    Currently Being Moderated
    thanks for ur reply ..