この質問は、私の別の質問に対する私の回答に関連しています。元の質問はここにあります
コメントで説明されている方法で悪いコードが失敗する理由を誰かが説明できますか(疑似コードであるwyによって)
// bad code
ResultSet rs = getDataFromDBMS("Select * from [tableName];");
//temp uses a collection member within it to hold a list of column names to data value pairs (hashmap<String,String>)
Object temp = new objectToHoldInfoFromResultSet();
// loop over the result set
while (rs.next)// for each row in the result set
{
for (int i = 1; i <= rs.getNumberColums; i++) {
temp.add(infoAboutColumn);
}
temp.printInfo();// always prints correct (ie current) info
//the print just takes the hashmap member and asks for a
//toString() on it
anotherObject(makeUseOf(temp));// always uses info from first
//iteration. Essentially grabs the hashMap member of temp, and puts
//this into another collection of type
//HashMap< HashMap<String,String>, temp> see the linked question
//for more detail.
}
// Seemingly each loop into the while the temp.doSomethingToData(); uses
// the temp object created in the first iteration
// good code
ResultSet rs = getDataFromDBMS("Select * from [tableName];");
// loop over the result set
while (rs.next)// for each row in the result set
{
Object temp = new objectToHoldInfoFromResultSet();// moving
// declaration
// of temp into
// the while
// loop solves
// the problem.
for (int i = 1; i <= rs.getNumberColums; i++) {
temp.add(infoAboutColumn);
}
temp.printInfo();// always prints correct (ie current) info
anotherObject(makeUseOf(temp));// also uses the correct (ie current)
// info.
}