문제

What is the difference between

public List<?> myList;

and

public List<String> myList;

I know the latter will store a List of myList objects (Strings) but am not sure what the first does.My guess is it will take object of any type.But is this safe?t

도움이 되었습니까?

해결책

Yes, its unsafe, that's why you can't add to it when using it as a parameter. You can only read from it.

List<?> means a list typed to an unknown type. This could be a List<A>, a List<B>, a List<String> etc.

Since you do not know what type the List is typed to, you can only read from the collection, and you can only treat the objects read as being Object instances.

public void processElements(List<?> elements){
   for(Object o : elements){
      System.out.println(o);
   }
}

In this method, you are not able to add things in "elements". Only read things, because you can't know what type the elements are.

다른 팁

As you already said, second will contain list of strings. First contains list of unknown objects and you need to explicilty cast them to proper objects before you use them. There would be other benifits with wild cards when you use them with inheritance like List<? extends ABC> etc. You need to go through the wildcard section of the java docs.

Here is a simple tutorial to understand them http://tutorials.jenkov.com/java-generics/wildcards.html

List<String> is a Parameterized Type representing a List which can contain objects of type String only whereas

List<?> is an Unbounded Wildcard Type representing a List that can contain only objects of some unknown type.

As per Effective Java, both are safe to use except for a List of Raw Type which can lead to exceptions at runtime and is provided only for compatibility and interoperability with legacy code written before the introduction of generics.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top