-
-
Save michiakig/9880618 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.*; | |
public class TypeSafety { | |
public static void main(String[] args){ | |
List<Set<?>> listOfWildcardSet = new ArrayList<Set<?>>(); | |
listOfWildcardSet.add(new HashSet<String>()); | |
listOfWildcardSet.add(new HashSet<Integer>()); | |
listOfWildcardSet.set(0, listOfWildcardSet.get(0)); | |
listOfWildcardSet.set(1, listOfWildcardSet.get(1)); | |
// ^^^ This is ok because listOfWildcardSet.get(int) returns a Set<?> | |
// and the type of listOfWildcardSet.set is void set(int, Set<?>) | |
List<Set> listOfRawSet = new ArrayList<Set>(); | |
// ^^^ This doesn't generate a warning although IMHO it should. but see below | |
listOfRawSet.add(new HashSet<String>()); | |
listOfRawSet.add(new HashSet<Integer>()); | |
listOfRawSet.set(0, listOfRawSet.get(0)); | |
listOfRawSet.set(1, listOfRawSet.get(1)); | |
// ^^^ This is also ok, because listOfRawSet.get returns a Set | |
// and listOfRawSet.set has the type of void set(int, Set) | |
/************************************** | |
* Here's where things start to differ: | |
**************************************/ | |
// Using the wildcard version: | |
Set<?> wild0 = listOfWildcardSet.get(0); | |
Set<?> wild1 = listOfWildcardSet.get(0); | |
/** | |
wild0.addAll(wild1); | |
^^^ This would generate an error at compile time: | |
Typesafety.java:28: cannot find symbol | |
symbol : method addAll(java.util.Set<capture#501 of ?>) | |
location: interface java.util.Set<capture#896 of ?> | |
wset0.addAll(wset1); | |
^ | |
I interpret the error message above by thinking that the two different <?> | |
are actually different types altogether. I think that any other version | |
would allowing potentially unsafe operations like those below... | |
*/ | |
// Using the raw version: | |
Set raw0 = listOfRawSet.get(0); | |
Set raw1 = listOfRawSet.get(0); | |
raw0.addAll(raw1); | |
// ^^^ No compile time error, BUT does generate a warning: | |
// warning: [unchecked] unchecked call to addAll(java.util.Collection<? extends E>) as a member of the raw type java.util.Set | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment