I want to create multiple objects inside while loop and access all objects outside in JAVA 8. Currently using a list to store the obects, but all objects get replaced by one last object (last created).
I have tried initializing list inside try, outside try, nothing works.
Here is my 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();
}
}
}
Here is my 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);
}
}
Here is my input file example (asd.txt)
hello|123
qwe|klj
It calls only the last object's printEncLoc function each time in the forEach line. It prints output as follows.
s1:qwe s2:klj
s1:qwe s2:klj
What is the problem here?