How to set o real copy of a hashtable inside a array in java?
I'm trying to do a arraylist of a hashtable for that i did:
ArrayList<java.util.Hashtable<Stri开发者_开发技巧ng, String>> info = new ArrayList<java.util.Hashtable<String, String>>();
this did the job but later i needed to add some hashtables inside info using a for cycle:
java.util.Hashtable<String, String> e = new java.util.Hashtable<String, String>();
while(rs.next()){
e.clear();
for(String a:dados){
e.put(a,rs.getString(a));
}
info.add(e);
}
The problem is that method add doesnt copy e to info, it only define a pointer to e so when i update e all inserted elements gets the new e values.
Can anyone give some help ?
thx for your time.
This should work:
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.Map;
import java.util.List;
List<Map<String, String>> info = new ArrayList<Map<String, String>>();
while (rs.next()) {
Map<String, String> e = new Hashtable<String, String>();
e.clear();
for (String a : dados) {
e.put(a, rs.getString(a));
}
info.add(e);
}
You should try to avoid declaring collections by their implementation class (declare them as List
instead of ArrayList
, or Map
instead of Hashtable
).
Don't need the clear() if you are using new everytime inside the loop.
java.util.Hashtable e = new java.util.Hashtable();
while(rs.next()){
e = new java.util.Hashtable();
for(String a:dados){
e.put(a,rs.getString(a));
}
info.add(e);
}
精彩评论