Last active
August 29, 2015 13:57
-
-
Save cab222/9878465 to your computer and use it in GitHub Desktop.
First two blocks compile and run, third block wouldn't if it was compiled
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
package test; | |
import com.google.common.collect.Lists; | |
import java.util.HashSet; | |
import java.util.List; | |
import java.util.Set; | |
public class TypeSafety { | |
public static void main(String[] args){ | |
List<Set<?>> listOfWildcardSet = Lists.newArrayList(); | |
listOfWildcardSet.add(new HashSet<String>()); | |
listOfWildcardSet.add(new HashSet<Integer>()); | |
listOfWildcardSet.set(0, listOfWildcardSet.get(0)); | |
listOfWildcardSet.set(1, listOfWildcardSet.get(1)); | |
List<Set> listOfRawSet = Lists.newArrayList(); //I thought this would generate a warnig the problem | |
listOfRawSet.add(new HashSet<String>()); | |
listOfRawSet.add(new HashSet<Integer>()); | |
listOfRawSet.set(0, listOfWildcardSet.get(0)); | |
listOfRawSet.set(1, listOfWildcardSet.get(1)); | |
/* | |
These alll generate unchecked warnings | |
*/ | |
List listRaw = Lists.newArrayList(); | |
listRaw.add(new HashSet<String>()); | |
listRaw.add(new HashSet<Integer>()); | |
listRaw.set(0, listRaw.get(0)); | |
listRaw.set(1, listRaw.get(1)); | |
List<Set<String>> listOfStringSet = Lists.newArrayList(); | |
listOfStringSet.add(new HashSet<String>()); | |
/* Doesnt compile, enforcing typesafety | |
listOfStringSet.add(new HashSet<Integer>()); | |
*/ | |
//It's all not very typesafe | |
Set<String> first = (Set<String>)listOfWildcardSet.get(0); | |
Set<Integer> second = (Set<Integer>)listOfWildcardSet.get(0); | |
Set<String> first2 = (Set<String>)listOfRawSet.get(0); | |
Set<Integer> second2 = (Set<Integer>)listOfRawSet.get(0); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment