练习。。
一. keySet()方式。
1 // 1.得到ServletContext 2 ServletContext context = this.getServletContext(); 3 4 // 2.直接取出访问次数. 5 Integer count = (Integer) context.getAttribute("count"); 6 7 // 3.判断count是否为null,如果为null说明是第一次访问. 8 if (count == null) { 9 count = 1; 10 } else { 11 count += 1;//count = count+1; 12 } 13 14 // 4.将count重新存储 15 context.setAttribute("count", count);
返回值是个只存放key值的Set集合(集合中无序存放的)
二. entrySet()方式。
1 Map<String, String> map = new HashMap<String, String>(); 2 map.put("01", "zhangsan"); 3 map.put("02", "lisi"); 4 map.put("03", "wangwu"); 5 //先获取map集合的所有键的Set集合,极为map中所有key值的集合 6 Set<String> keySet = map.keySet(); 7 //有了Set集合,就可以获取其迭代器。 8 Iterator<String> it = keySet.iterator(); 9 while (it.hasNext()) { 10 String key = it.next(); 11 //有了键可以通过map集合的get方法获取其对应的值。 12 String value = map.get(key); 13 //获得key和value值 14 System.out.println("key: " + key + "-->value: " + value); 15 }

浙公网安备 33010602011771号