44 * Created by CrowHawk on 17/2/16.
55 */
66
7+
8+ import java .lang .reflect .*;
79import java .util .*;
810
911public class GenericTest {
10- public static void main (String [] args ){
12+ public static void main (String [] args ) throws Exception {
1113 HashMap <String , Integer > hashMap = new HashMap <>();
1214 hashMap .put ("Tom" , 1 );
1315 hashMap .put ("Jerry" , 2 );
1416 hashMap .put ("Nick" , 3 );
17+ printHashmap (hashMap );
18+
19+ String [] array = new String []{"crow" ,"martin" ,"pattie" };
20+ swap (array , 1 , 2 );
21+ System .out .println ("array[2] = " + array [2 ]);
22+
23+ Method printMethod = GenericTest .class .getMethod ("printHashmap" , HashMap .class );
24+ Type [] types = printMethod .getGenericParameterTypes ();
25+ ParameterizedType parameterizedType = (ParameterizedType )types [0 ];
26+ Type [] actualTypes = parameterizedType .getActualTypeArguments ();
27+ System .out .println ("The paratype is " + parameterizedType .getRawType () + "<" + actualTypes [0 ] + "," + actualTypes [1 ] + ">" );
28+ }
29+
30+
31+ public static void printHashmap (HashMap <String , Integer > hashMap ){
1532 Set <Map .Entry <String , Integer >> entrySet = hashMap .entrySet ();
1633 for (Map .Entry <String , Integer > entry : entrySet ){
1734 System .out .println (entry .getKey () + "," + entry .getValue ());
@@ -23,4 +40,10 @@ public static void main(String[] args){
2340 System .out .println ("Value is " + entry .getValue ());
2441 }
2542 }
43+
44+ public static <T > void swap (T [] arr , int i , int j ){
45+ T tmp = arr [i ];
46+ arr [i ] = arr [j ];
47+ arr [j ] = tmp ;
48+ }
2649}
0 commit comments