java 泛型的嵌套(map例子)
package july7;
//泛型加Map的输出!
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TreeMap;
public class Demo20 {
public static void main(String[] args) {
Map<Integer, String> m = new TreeMap<Integer, String>();
m.put(1, "周冬雨");
m.put(2, "章子怡");
m.put(3, "章泽天");
System.out.println(m);
//第一种方式,用到了entrySet方法
Set<Entry<Integer, String>> s = m.entrySet();
Iterator<Entry<Integer, String>> it = s.iterator();
while(it.hasNext()){
Entry<Integer, String> e = it.next();//用到了泛型,这里消除了 强转!
System.out.println(e.getKey()+" "+e.getValue());
}
//第二种方法,用到了keySet方法
Set<Integer> set = m.keySet();
Iterator<Integer> iter = set.iterator();
while(iter.hasNext()){
Integer i = iter.next();//直接写到输出语句,出错!
System.out.println(i+" "+m.get(i));
}
}
}