注意:在此声明一下,我在复习时有的代码简写掉了,比如最后面的entry.key + entry.value; 应该是System.out.println(entry.key + entry.value); 前面的博客中好像也有这种现象,忘记和新手说了,sorry!~~~灰常抱歉!~~~
泛型(Generic)
解决元素存储的安全性问题
List l = new ArrayList();
l.add(123);
l.add("qin");
l.add("haha");
l.add(Person);
for(int i=0;i<list.size();i++){
//这里如果不进行判断,就会出现强制转换错误的
int score = (Integer)list.get(i);
System.out.println(score);
}
//可以使用泛型进行限制,让这个List只存储String类型或其他的唯一类型
List<String> l = new ArrayList<String>();
//l.add(123); 会编译错误
l.add("qin");
l.add("haha");
//l.add(Person); 会编译错误
for(int i=0;i<list.size();i++){
//这里如果不进行判断,就会出现强制转换错误的
String score = list.get(i);
System.out.println(score);
}
Iterator<String> i = l.iterator();
while(i.hasNext()){
i.next();
}
Map<String,Integer> m = new HashMap<String,Integer>();
m.put("haha",23);
m.put("lala",25);
Set<Map.Entry<String,Integer>> s = m.entrySet();
for(Map.Entry<String,Integer> entry: s){
entry.key + entry.value;
}