java泛型的使用

时间:2021-07-10 00:08:11
package com.wzh.test.generic;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set; import org.junit.Test; public class Demo1 { @Test
public void test1(){
//List是接口,ArrayList是具体实现
List<String> list=new ArrayList<String>();
list.add("12");
list.add("f");
System.out.println(list); //传统迭代
Iterator<String> it=list.iterator();
while(it.hasNext()){
String value=it.next();
System.out.println(value);
} //增强for
for(String s : list){
System.out.println(s);
}
} @Test
public void test2(){
//Map是接口,HashMap是具体实现
//HashMap存入后无顺序,LinkedHashMap以存入顺序存储
//Map<Integer,String> map=new HashMap<Integer,String>();
Map<Integer,String> map=new LinkedHashMap<Integer, String>();
map.put(3, "cc");
map.put(2, "bb");
map.put(1, "aa"); //传统 keyset entryset
Set<Map.Entry<Integer,String>> set=map.entrySet();
Iterator<Map.Entry<Integer, String>> it=set.iterator();
while(it.hasNext()){
Map.Entry<Integer, String> entry=it.next();
int key=entry.getKey();
String value=entry.getValue();
System.out.println(key+":"+value);
} //增强for循环
for(Map.Entry<Integer, String> m : map.entrySet()){
int key=m.getKey();
String value=m.getValue();
System.out.println(key+":"+value);
} }
}