我有 2 个数组列表:
ArrayList<ArrayList<String>> res= new ArrayList();
ArrayList<String> data= new ArrayList();
将结果集添加到子级并将子级附加到父级后,我在 data
上调用 .clear()
来重置索引。
问题在于 .clear()
会同时删除子级和父级。
有什么想法吗?
最后,从整个结果集中,我只将最后一行重复了 10 次。
public ArrayList<ArrayList<String>> getTemplateTableData() {
ArrayList<ArrayList<String>> res = new ArrayList();
ArrayList<String> data = new ArrayList();
CDb cb = new CDb();
OracleConnection conn = cb.getConn();
OraclePreparedStatement ps = null;
OracleResultSet rs = null;
OracleResultSetMetaData rsm = null;
try {
ps = (OraclePreparedStatement)
conn.prepareStatement("Select * From Va_User_Infos_V t Where t.User_Id = 1");
ps.execute();
rs = (OracleResultSet)ps.getResultSet();
rsm = (OracleResultSetMetaData)rs.getMetaData();
while(rs.next()) {
int col = 2;
data.clear();
System.out.println(data);
while(col < rsm.getColumnCount()) {
col++;
data.add(rs.getString(col));
}
res.add(data);
System.out.println(data);
}
System.out.println(res);
} catch(Exception e) {
e.printStackTrace();
} finally {
cb.done(rs);
cb.done(ps);
cb.done(conn);
}
return res;
}
输出:
[]
[1Col-1, Col-2, Col-3, Col-4, Col-5, Col-6, Col-7, Col-8]
[]
[2Col-1, Col-2, Col-3, Col-4, Col-5, Col-6, Col-7, Col-8]
[]
[3Col-1, Col-2, Col-3, Col-4, Col-5, Col-6, Col-7, Col-8]
[]
[4Col-1, Col-2, Col-3, Col-4, Col-5, Col-6, Col-7, Col-8]
[]
[5Col-1, Col-2, Col-3, Col-4, Col-5, Col-6, Col-7, Col-8]
[]
[6Col-1, Col-2, Col-3, Col-4, Col-5, Col-6, Col-7, Col-8]
[]
[7Col-1, Col-2, Col-3, Col-4, Col-5, Col-6, Col-7, Col-8]
[]
[8Col-1, Col-2, Col-3, Col-4, Col-5, Col-6, Col-7, Col-8]
[]
[9Col-1, Col-2, Col-3, Col-4, Col-5, Col-6, Col-7, Col-8]
[]
[10Col-1, Col-2, Col-3, Col-4, Col-5, Col-6, Col-7, Col-8]
[[10Col-1, Col-2, Col-3, Col-4, Col-5, Col-6, Col-7, Col-8],
[10Col-1, Col-2, Col-3, Col-4, Col-5, Col-6, Col-7, Col-8],
[10Col-1, Col-2, Col-3, Col-4, Col-5, Col-6, Col-7, Col-8],
[10Col-1, Col-2, Col-3, Col-4, Col-5, Col-6, Col-7, Col-8],
[10Col-1, Col-2, Col-3, Col-4, Col-5, Col-6, Col-7, Col-8],
[10Col-1, Col-2, Col-3, Col-4, Col-5, Col-6, Col-7, Col-8],
[10Col-1, Col-2, Col-3, Col-4, Col-5, Col-6, Col-7, Col-8],
[10Col-1, Col-2, Col-3, Col-4, Col-5, Col-6, Col-7, Col-8],
[10Col-1, Col-2, Col-3, Col-4, Col-5, Col-6, Col-7, Col-8],
[10Col-1, Col-2, Col-3, Col-4, Col-5, Col-6, Col-7, Col-8]]
最终目的是解析父列表并将数据添加到XWPF docx表中。
解决方案:
while(rs.next()) {
int col = 2;
data.clear();
while(col < rsm.getColumnCount()) {
col++;
data.add(rs.getString(col));
}
ArrayList clone = (ArrayList)data.clone();
res.add(clone);
}
最佳答案
您正在做什么:将对子列表的引用放入父列表中。
您没有创建子列表的副本。只需将对相同列表的引用放在不同的位置即可。
惊喜:当您现在修改该子列表时(无论您做什么:添加、删除、清除、排序...)所有其他引用都会向您显示更改的内容!
两种解决方案:
- 创建新子列表;并且在将列表添加到父列表 后不要对其进行修改
- “扁平化”你的家长列表(也将其设为
List<String>
);并使用addAll()
添加子列表的内容!
关于Java ArrayList<ArrayList<String>> 子级上的clear() 清除父级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43517226/