package cn.wonders.generic
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 java.util.Map.Entry
import org.junit.Test
public class GenericTest {
@Test
public void run(){
List <String> list = new ArrayList<String>()
list.add("a")
list.add("b")
list.add("c")
System.out.println("-----普通for循环-----")
for(int i=0
System.out.println(list.get(i))
}
System.out.println("-----增强for循环-----")
for(String l:list){
System.out.println(l)
}
System.out.println("-----迭代器-----")
Iterator<String> iterator = list.iterator()
while(iterator.hasNext()){
System.out.println(iterator.next())
}
}
@Test
public void run2(){
Set<String>set = new HashSet<String>()
set.add("alex")
set.add("jungle")
set.add("shrill")
Iterator<String> iterator = set.iterator()
System.out.println("----------迭代器-----")
while(iterator.hasNext()){
System.out.println(iterator.next())
}
System.out.println("----------增强for循环-----")
for(String s:set){
System.out.println(s)
}
}
@Test
public void run3(){
Map<String,Integer>map = new HashMap<String, Integer>()
map.put("shrill", 1)
map.put("jungle", 2)
map.put("mecxio", 3)
System.out.println("使用键的集合处理")
Set<String> keySet = map.keySet()
for(String s:keySet){
System.out.println(s+":"+map.get(s))
}
System.out.println("使用键值对的集合处理")
Set<Entry<String, Integer>> entrySet = map.entrySet()
for(Entry<String, Integer> en:entrySet){
System.out.println(en.getKey()+":"+en.getValue())
}
}
}
——————————————————————————————-
package cn.wonders.generic;
import java.util.Arrays;
import org.junit.Test;
public class AdGenericTest {
/**
*
* 测试泛型集合
*/
@Test
public void run(){
Integer[] arr = new Integer[]{1,2,3,4,5,6};
change(arr,1,3);
System.out.println(Arrays.toString(arr));
String[] strarr = new String[]{"aa","bb","cc","dd","ee","ff"};
change(strarr,1,3);
System.out.println(Arrays.toString(strarr));
reset(strarr);
System.out.println(Arrays.toString(strarr));
}
/**
* 自定义泛型方法
* 定义泛型 <T> 放在返回值前面
* @param arr
* @param idx1
* @param idx2
*/
public <T> void change(T[]arr,int idx1,int idx2){
T temp = arr[idx1];
arr[idx1] = arr[idx2];
arr[idx2] = temp;
}
public void change(Integer[] arr, int idx1, int idx2) {
int temp = arr[idx1];
arr[idx1] = arr[idx2];
arr[idx2] = temp;
}
public void change(String[] arr, int idx1, int idx2) {
String temp = arr[idx1];
arr[idx1] = arr[idx2];
arr[idx2] = temp;
}
/**
* 颠倒所有的元素
* @param <T>
* @param arr
*/
public <T> void reset(T [] arr){
for(int i=0;i<arr.length/2;i++){
T temp = arr[i];
arr[i] = arr[arr.length-i-1];
arr[arr.length-i-1] = temp;
}
}
}