gpt4 book ai didi

java - 在 Loop 内部创建多个 Java 对象并使用外部的所有对象

转载 作者:行者123 更新时间:2023-12-02 09:39:06 25 4
gpt4 key购买 nike

我想在 while 循环内创建多个对象并访问 JAVA 8 外部的所有对象。当前使用列表来存储对象,但所有对象都会被最后一个对象(最后创建的)替换。

我尝试过在尝试内初始化列表,在尝试外初始化列表,但没有任何效果。

这是我的 test1.java,

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class test1 {
public static void main(String[] args){
try {
List<test2> objList=new ArrayList<>();
BufferedReader encReader = new BufferedReader(new FileReader("./asd.txt"));
String eachLine;
while ((eachLine = encReader.readLine()) != null) {
String[] data = eachLine.split("\\|");
if(true){
objList.add(new test2(data[0], data[1]));
}
} // While ends here

objList.forEach(x -> x.printEncLoc());

}catch (IOException e) {
e.printStackTrace();
}
}
}

这是我的 test2.java,

public class test2 {
private static String s1;
private static String s2;
test2(String s1new, String s2new){
s1=s1new;
s2=s2new;
}
public static void printEncLoc(){
System.out.println("s1:"+s1+" s2:"+s2);
}
}

这是我的输入文件示例(asd.txt)

hello|123
qwe|klj

每次在 forEach 行中仅调用最后一个对象的 printEncLoc 函数。它打印输出如下。

s1:qwe s2:klj
s1:qwe s2:klj

这里有什么问题吗?

最佳答案

您将 test2 中的属性设置为静态,这意味着所有实例共享相同的属性。因此,当您更改第二行的它们时,第一行也会更改。

从 s1 和 s2 以及 printEncLoc() 方法中删除“静态”,您的代码就可以正常工作。

编辑:参见 https://www.baeldung.com/java-static有关静态工作原理的更多信息

关于java - 在 Loop 内部创建多个 Java 对象并使用外部的所有对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57248536/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com