Skip to content

Commit a163370

Browse files
author
CrowHawk
committed
Generic2
1 parent 0a72cd4 commit a163370

1 file changed

Lines changed: 24 additions & 1 deletion

File tree

Basic-java/src/com/crow/Generic/GenericTest.java

Lines changed: 24 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,14 +4,31 @@
44
* Created by CrowHawk on 17/2/16.
55
*/
66

7+
8+
import java.lang.reflect.*;
79
import java.util.*;
810

911
public 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

Comments
 (0)