Created
June 11, 2012 07:23
-
-
Save itang/2908890 to your computer and use it in GitHub Desktop.
Java 协变
This file contains 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.ArrayList; | |
import java.util.List; | |
interface A { } | |
class B implements A { } | |
public class TT { | |
@SuppressWarnings("unchecked") | |
public static void main(String[] args) { | |
// List<A> listA = new ArrayList<B>(); //Type mismatch: cannot convert from ArrayList<B> to List<A> | |
// List<A> listA = (List<A>)new ArrayList<B>(); //Cannot cast from ArrayList<B> to List<A> | |
List<? extends A> listSomeA = new ArrayList<B>(); // ? extends A | |
test_magic(); | |
} | |
public static void test_magic() { | |
ArrayList<B> listB = new ArrayList<B>(); | |
listB.add(new B()); | |
List<A> listA1 = magic_cast(listB); | |
for (A a : listA1) { | |
System.out.println(a); | |
} | |
List<A> listA2 = conv(listB); | |
for (A a : listA2) { | |
System.out.println(a); | |
} | |
} | |
private static List<A> magic_cast(ArrayList<B> listB) { | |
List<?> listAny = listB; | |
List<A> listA = (List<A>) listAny; | |
return listA; | |
} | |
private static List<A> conv(ArrayList<B> listB) { | |
List<A> listA = new ArrayList<A>(); | |
for (B b : listB) { | |
listA.add(b); | |
} | |
return listA; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment