![]() |
Sponsored Link •
|
Summary
I set out to explore how the compiler treats a plain List vs. a List<?>, and in the process found something mysterious.
Advertisement
|
A raw List can hold any type, whereas a List<?> holds an unknown, but specific type. That is, List is a heterogeneous container, while List<?> is a homogeneous container. However, I had observed that the compiler tends to accept either without warning, so I wrote the following example to explore this:
import java.util.*; public class UnboundedWildcards1 { static List list1; static List<?> list2; static List<? extends Object> list3; static void assign1(List list) { list1 = list; list2 = list; // list3 = list; // Warning: unchecked conversion // Found: List, Required: List<? extends Object> } static void assign2(List<?> list) { list1 = list; list2 = list; list3 = list; } static void assign3(List<? extends Object> list) { list1 = list; list2 = list; list3 = list; } public static void main(String[] args) { assign1(new ArrayList()); assign2(new ArrayList()); // assign3(new ArrayList()); // Warning: // Unchecked conversion. Found: ArrayList // Required: List<? extends Object> assign1(new ArrayList<String>()); assign2(new ArrayList<String>()); assign3(new ArrayList<String>()); // Both forms are acceptable as List<?>: List<?> wildList = new ArrayList(); wildList = new ArrayList<String>(); assign1(wildList); assign2(wildList); assign3(wildList); } }
So even though List and List<?> are technically different types, the compiler treats them interchangeably.
What I was not expecting was that it treats List<?> differently than List<? extends Object>. Perhaps someone knows the explanation.
Have an opinion? Readers have already posted 9 comments about this weblog entry. Why not add yours?
If you'd like to be notified whenever Bruce Eckel adds a new entry to his weblog, subscribe to his RSS feed.
![]() | Bruce Eckel (www.BruceEckel.com) provides development assistance in Python with user interfaces in Flex. He is the author of Thinking in Java (Prentice-Hall, 1998, 2nd Edition, 2000, 3rd Edition, 2003, 4th Edition, 2005), the Hands-On Java Seminar CD ROM (available on the Web site), Thinking in C++ (PH 1995; 2nd edition 2000, Volume 2 with Chuck Allison, 2003), C++ Inside & Out (Osborne/McGraw-Hill 1993), among others. He's given hundreds of presentations throughout the world, published over 150 articles in numerous magazines, was a founding member of the ANSI/ISO C++ committee and speaks regularly at conferences. |
Sponsored Links
|