java - 为什么 ArrayList 总是返回最后一个对象?
问题描述
我正在使用 ArrayList 从另一个对象获取数据,问题是我总是将数组的最后一个元素作为输出
这是我的功能:
public ArrayList<CheckResults> extractCheckingResults() {
CheckResults resultRow = new CheckResults();
ArrayList<CheckResults> results = new ArrayList<CheckResults>();
//Getting the size of the table
int rowNum = iplist.length;
// Fetching the data from the table
for (int i = 0; i < rowNum; i++) {
resultRow.setId(id.getText());
resultRow.setIp(ip.getText());
resultRow.setDomain(domain.getText());
results.add(resultRow);
}
results.forEach(row -> {
System.out.print("\n");
System.out.print("ID: " + row.getId().toString() + "\n");
System.out.print("IP: " + row.getIp().toString() + "\n");
System.out.print("Domain: " + row.getDomain().toString() + "\n");
System.out.print("----------------------------------------------\n");
});
return results;
}
resultRow
Object 用于获取数据并将其设置为下results
一个空索引
这是我运行此函数时得到的输出:
ID: 9
IP: 1.2.3.4 (same ip)
Domain: www.same-domain.com
----------------------------------------------
ID: 9
IP: 1.2.3.4 (same ip)
Domain: www.same-domain.com
----------------------------------------------
ID: 9
IP: 1.2.3.4 (same ip)
Domain: www.same-domain.com
----------------------------------------------
ID: 9
IP: 1.2.3.4 (same ip)
Domain: www.same-domain.com
----------------------------------------------
ID: 9
IP: 1.2.3.4 (same ip)
Domain: www.same-domain.com
----------------------------------------------
ID: 9
IP: 1.2.3.4 (same ip)
Domain: www.same-domain.com
----------------------------------------------
ID: 9
IP: 1.2.3.4 (same ip)
Domain: www.same-domain.com
----------------------------------------------
我不明白问题出在哪里
解决方案
CheckResults resultRow = new CheckResults();
创建CheckResults
. 然后,您修改该实例并将其多次添加到同一个List
. 您需要创建新实例以添加到您List
的循环中。喜欢,
for (int i = 0; i < rowNum; i++) {
CheckResults resultRow = new CheckResults();
resultRow.setId(id.getText());
resultRow.setIp(ip.getText());
resultRow.setDomain(domain.getText());
results.add(resultRow);
}
推荐阅读
- linux - NGINX 读取文件夹中新文件的自动权限
- flask - 烧瓶类型错误:“NoneType”不可下标
- python - Python 3.8:为什么即使 if 语句为 false,new_list 也会被更新?
- python - 如何在 pandas groupby 操作中计算 lambda 函数并同时添加一个 size 列?
- django - 找不到 Django 管理员和 wagtail 静态文件
- tensorboard - 如何在张量板上跟踪训练有素的张量流对象检测 api 的准确性
- typescript - Typescript如何检查具有多种类型的对象的类型
- python - UDP客户端错误:ConnectionResetError:[WinError 10054]一个现有的连接被远程主机强行关闭
- android - Android复选框在recyclerview中的片段上不可点击
- python-3.x - 我从 Heroku 收到关于 Discord Intents 的错误 (Discord.py)