今天碰到了一個關於對象和對象引用的問題。
才注意到原來java中對象和對象的引用的問題無處不在。
問題出現在hashmap中,將對象存入hashmap時,不能將一個對象反覆使用,
比如對象A.a=1,A.b=2, map.put(key,A);如果再修改A的屬性值,如A.a=10,A.b=20,然後 map.put(key,A).
這樣存入map中的值將永遠只有一個,就是最後一個對象A。
從map中取出時也一樣,要new對象A來取出每一個map中的對象A.
謹記,java中,對象的問題無處不在。
public void loadgroup(){ //todo load alarm group AlarmName alarm = new AlarmName(); // 不能在這裏new Connection conn = null;// getConnection(); try { conn = getConnection(); String sqlSelect = "select * from alarmname"; PreparedStatement st = conn.prepareStatement(sqlSelect); ResultSet RS = st.executeQuery(); while (RS.next()) { alarm.setalnamedata(RS.getInt("id"), RS.getString("alarmname"), RS.getString("roles"), RS.getString("descp")); // 從數據庫讀出group數據 alarmNameMap.put(alarm.alarmname, alarm); } st.close(); } catch (Exception e) { CommonForBoth.ReFailed(ErrorCode.GConnectDBFailORsqlIllegal); e.printStackTrace(); return ; } finally { try { conn.close(); } catch (Exception e1) { e1.printStackTrace(); CommonForBoth.ReFailed(ErrorCode.GDBCloseError); } } } public void loadperson(){ //todo load person Connection conn = null; // getConnection(); try { conn = getConnection(); String sqlSelect = "select * from role"; PreparedStatement st = conn.prepareStatement(sqlSelect); ResultSet RS = st.executeQuery(); while (RS.next()) { Role role = new Role(); // 應該在這裏new role.setroledata(RS.getInt("roleid"), RS.getString("name"), RS.getString("descp"), RS.getString("email"), RS.getString("phone")); roleMap.put(role.name, role); } st.close(); } catch (Exception e) { logger.warn(ErrorCode.ConnectDBFailORsqlIllegal); e.printStackTrace(); return ; } finally { try { conn.close(); } catch (Exception e1) { logger.warn(ErrorCode.ConnectDBFailORsqlIllegal); e1.printStackTrace(); } } }