我想在 while 循環(huán)內創(chuàng)建多個對象并訪問 JAVA 8 外部的所有對象。目前使用列表來存儲對象,但所有對象都被最后一個對象(最后創(chuàng)建的)替換。我已經(jīng)嘗試在嘗試中初始化列表,在嘗試之外,但沒有任何效果。這是我的 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|123qwe|klj它每次在 forEach 行中只調用最后一個對象的 printEncLoc 函數(shù)。它打印輸出如下。s1:qwe s2:kljs1:qwe s2:klj這里有什么問題?
1 回答

拉丁的傳說
TA貢獻1789條經(jīng)驗 獲得超8個贊
您將 test2 中的屬性設為靜態(tài),這意味著所有實例共享相同的屬性。因此,當您為第二行更改它們時,第一行也會更改。
從 s1 和 s2 以及您的 printEncLoc() 方法中刪除“static”,您的代碼就可以工作了。
添加回答
舉報
0/150
提交
取消