File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ package btp .oneP ;
2+
3+ import java .lang .reflect .Method ;
4+ import java .util .ArrayList ;
5+
6+ public class GenericErase {
7+
8+ public static void main (String [] args ) {
9+ ArrayList <String > sl = new ArrayList <String >();
10+ sl .add ("Magic" );
11+ Class <? extends ArrayList > clazz = sl .getClass ();
12+ try {
13+ Method method = clazz .getMethod ("add" , Object .class );
14+ method .invoke (sl , 1 );
15+ System .out .println (sl );
16+ //out:[Magic, 1]
17+ }catch (Exception e ){
18+ e .printStackTrace ();
19+ }
20+ }
21+
22+ }
Original file line number Diff line number Diff line change 1+ package btp .oneP ;
2+
3+ import java .util .ArrayList ;
4+ import java .util .Collection ;
5+
6+ public class GenericEvaluate {
7+
8+ public static void main (String [] args ) {
9+ Collection <Pair <String ,Long >> c1 = new ArrayList <Pair <String ,Long >>();
10+ Collection <Pair <String ,Long >> c2 = c1 ;
11+ //Collection<Pair<String,?>> c3 = c1;
12+ Collection <? extends Pair <String ,?>> c4 = c1 ;
13+
14+ Collection <SubTypeOfPair <String ,Long >> c5 = new ArrayList <SubTypeOfPair <String ,Long >>();
15+ //Collection<Pair<String,Long>> c6 = c5;
16+ Collection <SubTypeOfPair <String ,Long >> c7 = c5 ;
17+ //Collection<Pair<String,?>> c8 = c5;
18+ Collection <? extends Pair <String ,?>> c9 = c5 ;
19+ }
20+
21+ }
22+
23+ class Pair <K ,V >{
24+
25+ }
26+
27+ class SubTypeOfPair <K ,V > extends Pair <K , V >{
28+
29+ }
Original file line number Diff line number Diff line change 1+ package btp .oneP ;
2+
3+ import java .util .ArrayList ;
4+ import java .util .Arrays ;
5+ import java .util .List ;
6+
7+ public class ListCopy {
8+
9+ public static <T > void copy (List <? extends T > src ,List <? super T > dest ){
10+ for (T t :src ){
11+ dest .add (t );
12+ }
13+ }
14+
15+ public static void main (String [] args ) {
16+ List <String > sList = new ArrayList <String >(Arrays .<String >asList (new String []{"hehe" ,"xixi" ,"caca" }));
17+ List <Object > oList = new ArrayList <Object >();
18+ copy (sList ,oList );
19+ for (Object o :oList ){
20+ System .out .println (o );
21+ }
22+ }
23+
24+ }
You can’t perform that action at this time.
0 commit comments