/**
* 在使用泛型时,如果两边同时用到了泛型,两边必须一致,例:ArrayList<String> list = new ArrayList<String>();
* 在使用泛型时,如果仅一边用到了泛型,这是可以的,为了保持向后兼容性,例: ArrayList<String> list = new ArrayList(); ArrayList list = new ArrayList<String>();
*/
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.junit.Test;
public class generic {
public static void main(String[] args) {
List<String> list1 = new ArrayList<String>();
list1.add("bbb");
list1.add("cc");
list1.add("ddd");
list1.add("eeee");
list1.add("ffffd");
//方式1
Iterator<String> Strs = list1.iterator();
while (Strs.hasNext()){
System.out.println(Strs.next());
}
//方式2
for (String s : list1){
System.out.println(s);
}
Set<Integer> set = new HashSet<Integer>();
set.add(1);
set.add(2);
set.add(3);
set.add(4);
set.add(5);
set.add(8);
set.add(7);
//方式1
for (Integer i : set){
System.out.println(i);
}
Map<Integer, String> map = new HashMap<Integer, String>();
map.put(1, "eboy");
map.put(2, "FRR");
map.put(3, "LJ");
//方式1
Set<Integer> set1 = map.keySet();
Iterator<Integer> it = set1.iterator();
while (it.hasNext()){
int key = it.next();
System.out.println(map.get(key));
}
//方式2
Set<Map.Entry<Integer, String>> set2 = map.entrySet();
Iterator<Map.Entry<Integer, String>> it2 = set2.iterator();
while (it2.hasNext()){
Map.Entry<Integer, String> entry = it2.next();
System.out.println(entry.getKey() + ": " + entry.getValue());
}
//方式3 1.5
for (Map.Entry<Integer, String> entry3 : map.entrySet()){
System.out.println(entry3.getKey() + ": " + entry3.getValue());
}
String arr[] = {"a", "b", "c", "d"};
System.out.println(arr[0]);
reverse(arr);
System.out.println(arr[0]);
}
//加个@Text,可用JUnit单独测试test2方法
@Test
public void test2(){
int i;
i = 15;
String s;
s = "asfdsaf";
System.out.println("test" + i + s);
}
//自定义泛型:方法是泛型
public static <T> void Test(T t){
}
//自定义泛型:返回值是泛型
public static <T, E> T Test1(T t, E e){
return null;
}
//泛型应用实例:交换数组元素
static <T> void swap(T arr[], int pos1, int pos2){
T temp = arr[pos1];
arr[pos1] = arr[pos2];
arr[pos2] = temp;
}
//泛型应用实例:接收一个任意数组,并颠倒数组中的所有元素
static <T> void reverse(T arr[]){
int pos1 = 0;
int pos2 = arr.length - 1;
T temp = null;
while (pos1 <= pos2){
temp = arr[pos1];
arr[pos1] = arr[pos2];
arr[pos2] = temp;
pos1++;
pos2--;
}
}
}