首页 > 解决方案 > 为什么 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;
    }

resultRowObject 用于获取数据并将其设置为下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
----------------------------------------------

我不明白问题出在哪里

标签: java

解决方案


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);
}

推荐阅读