有一个Map对象,这时候使用keySet()方法获取所有的key值,比如:
Map map = new HashMap();
map.put(1, "a");
map.put(2, "b");
map.put(3, "c");
map.put(4, "d");
Set keys1 = map.keySet();
Set keys2 = map.keySet();
Set keys3 = map.keySet();
上面三个set对象key1,key2,key3引用的是一个对象。这时map的keySet()方法只返回一个set实例,所以当从key1中删除一个对象时候,key2和key3将会受到影响。
keys1.remove(1);
System.out.println(keys1);
System.out.println(keys2);
System.out.println(keys3);
打印结果为:
[2, 4, 3]
[2, 4, 3]
[2, 4, 3]
下面是摘自API帮助文档的说明
keySet
public Set<K> keySet()返回此映射中所包含的键的 set 视图。该集合受映射的支持,所以映射的变化也反映在该集合中,反之亦然。该集合支持元素的移除,通过 Iterator.remove、Set.remove、removeAll、retainAll 和 clear 操作,从该映射中移除相应的映射关系。它不支持 add 或 addAll 操作。
指定者:
接口 Map<K,V> 中的 keySet
覆盖:
类 AbstractMap<K,V> 中的 keySet
返回:
此映射所包含的键的 set 视图。
关于Map的for 循环
根据JDK5的新特性,用For循环Map,例如循环Map的Key
注意的是,paraMap 是怎么样定义的,如果是简单的Map paraMap = new HashMap ();那前面的String就只能换成Object了.
循环整个map的key和value
Map<Integer,String> map = new LinkedHashMap<Integer,String>();
map.put(1, "星期一");
map.put(2, "星期二");
map.put(3, "星期三");
map.put(4, "星期四");
map.put(5, "星期五");
map.put(6, "星期六");
map.put(7, "星期日");
for(Map.Entry<Integer, String> entry: map.entrySet()) {
System.out.print(entry.getKey() + ":" + entry.getValue() + "\t");
}
輸出結果:
1:星期一 2:星期二 3:星期三 4:星期四 5:星期五 6:星期六 7:星期日
//增加和修改学生
JSONObject jsonObject = JSONObject.fromObject(json_info);
TableBean studentTB_modify = new TableBean("TN_STUDENT_MODIFY");
TableBean studentTB_new = new TableBean("TN_STUDENT_NEW");
dataBean.addTableBean(studentTB_modify);
dataBean.addTableBean(studentTB_new);
if (jsonObject != null && jsonObject.size() > 0 && !"{}".equals(jsonObject)) {
@SuppressWarnings("unchecked")
Set<String> classIdSet = jsonObject.keySet();
for(String classId : classIdSet){
JSONArray jsonArray_student = jsonObject.getJSONArray(classId);
for (int i = 0; i < jsonArray_student.size(); i++) {
JSONObject jsonObj_sub = (JSONObject) jsonArray_student.get(i);
String studentId = (String) jsonObj_sub.get("studentId");
String studentName = (String) jsonObj_sub.get("studentName");
String studentAge = (String) jsonObj_sub.get("studentAge");
RowBean rowBean = new RowBean();
rowBean.addCellBean(new CellBean("CN_STUDENT_NAME", studentName));
rowBean.addCellBean(new CellBean("CN_STUDENT_AGE", studentAge));
rowBean.addCellBean(new CellBean("CR_CLASS_CAOHONG_ID", classId));
if (StringUtils.isNotBlank(studentId)) {
rowBean.addCellBean(new CellBean(TriangleDefinition.COLUMN_NAME_CN_ID, studentId));
studentTB_modify.addRowBean(rowBean);
}else{
studentTB_new.addRowBean(rowBean);
}
}
}
}