我从数据库中检索值,创建一个新的Transaction Object并将其添加到ArrayList<Transaction>
,然后我返回。
问题在于,每次调用returnList.add(t);
时,它都会替换所有旧事务,而不是仅添加事务。
导致此行为的错误在哪里?
public ArrayList<Transaction> getTransactions(long intervall, Map<String, String> transactionFields) {
connect();
ArrayList<Transaction> returnList = new ArrayList<Transaction>();
Statement sta;
ZonedDateTime now = ZonedDateTime.now(ZoneOffset.UTC);
now = now.minusSeconds(intervall);
try {
sta = conn.createStatement();
String Sql = "...";
ResultSet rs = sta.executeQuery(Sql);
while (rs.next()) {
Transaction t = new Transaction(rs.getString("No"), transactionFields);
t.set("AgentName", rs.getString("cname"));
returnList.add(t);
}
} catch (SQLException e) {
...
}
disconnect();
return returnList;
}
这是Transaction类:
public class Transaction {
private Map<String, String> fields;
public Transaction(String number, Map<String, String> transactionFields) {
fields = transactionFields;
fields.put("Number", number);
}
public void set(String field, String value) {
fields.put(field, value);
}
public String get(String field) {
return fields.get(field);
}
public Map<String, String> getFieldMap() {
return fields;
}
@Override
public String toString() {
return fields.toString();
答案 0 :(得分:4)
您在所有Map
个实例中使用相同的Transaction
。
相反,每次传递一个新的:
Transaction t = new Transaction(rs.getString("No"), new HashMap<String, String>());
或只在Map
课程中创建Transaction
。