package tryAny.effectiveJava;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
public class GenericsTest1 {
public static void main(String[] args) {
final Collection stamps = Arrays.asList(new Stamp(), new Stamp(), "");
//The following code will detect it as a compile error.
// final Collection<Stamp> stamps = Arrays.asList(new Stamp(), new Stamp(), "");
for (Iterator i = stamps.iterator(); i.hasNext();) {
Stamp stamp = (Stamp) i.next(); //Send an error when casting the third element. Only known at run time.
System.out.println("cast success");
}
}
static class Stamp {
}
}
package tryAny.effectiveJava;
import java.util.ArrayList;
import java.util.List;
public class GenericsTest2 {
public static void main(String[] args) {
List<String> strings = new ArrayList<>();
unsafeAdd(strings, Integer.valueOf(42));
String s = strings.get(0); // Has compiler-generated cast
}
private static void unsafeAdd(List list, Object o) {
//The following code will cause a compile error.
// private static void unsafeAdd(List<Object> list, Object o) {
list.add(o);
}
}
package tryAny.effectiveJava;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class GenericsTest3 {
public static void main(String[] args) {
Set<?> s1 = Stream.of("2", "b", 1).collect(Collectors.toSet());
Set s2 = Stream.of("2", "c", 1).collect(Collectors.toSet());
// s1.add("c"); //This code will result in a compilation error
s2.add("b");
System.out.println(numElementsInCommon(s1, s2));
}
// Use of raw type for unknown element type - don't do this!
static int numElementsInCommon(Set<?> s1, Set<?> s2) {
int result = 0;
for (Object o1 : s1)
if (s2.contains(o1))
result++;
return result;
}
}
// Legitimate use of raw type - instanceof operator
if (o instanceof Set) { // Raw type
Set<?> s = (Set<?>) o; // Wildcard type
...
}
Recommended Posts