I have a MyData class representing an input of strings, which I also added to a list and parsed individually into an array.
class MyData{
private String data1;
private String data2;
private int data3;
public MyData(String d1, String d2, int d3){
this.data1=d1;
this.data2=d2;
this.data3=d3;
}
//getter and setter
}
String str1="IRC00001 blue 2017";
String str2="IRC00002 red 2019";
String str3="IRC00003 black 2020";
List<String>list=new ArrayList<String>();
list.add(str1);
list.add(str2);
list.add(str3);
for(String s:list) {
String[] parts=s.split(" ");
String number=parts[0];
String colour=parts[1];
String y=parts[2];
int year=Integer.parseInt(y);
I am trying to create a MyData object for each String in a for loop, this is necessary because there is a large number of strings (not in this example) and the user won't be able to initialize each of them individually. However when I try to use them they all have been overwritten by the last entry of the list. Is there a way to initialize each object in a loop, and if yes, how can I name a variable for each of them?
I'm sorry if this question has been asked multiple times. I just could't find a way to make it work on my example.
```
List<MyData>myList=new ArrayList<MyData>();
for(String string1:list) {
myList.add(new MyData(number,colour,year));
}
for(MyData data:myList) {
System.out.print(data.getYear());
}
//prints:
//2020 2020 2020
CodePudding user response:
import java.util.ArrayList;
import java.util.List;
public class SOF {
public static void main(String[] arg) {
SOF s= new SOF();
s.test();
}
public void test(){
String str1 = "IRC00001 blue 2017";
String str2 = "IRC00002 red 2019";
String str3 = "IRC00003 black 2020";
List<String> list = new ArrayList<String>();
list.add(str1);
list.add(str2);
list.add(str3);
List<MyData> myList = new ArrayList<MyData>();
for (String s : list) {
String[] parts = s.split(" ");
String number = parts[0];
String colour = parts[1];
String y = parts[2];
int year = Integer.parseInt(y);
myList.add(new MyData(number, colour, year));
}
for (MyData data : myList) {
System.out.print(" " data.getData3());
}
}
}
class MyData{
private String data1;
private String data2;
private int data3;
public MyData(String d1, String d2, int d3){
this.data1=d1;
this.data2=d2;
this.data3=d3;
}
public String getData1() {
return data1;
}
public void setData1(String data1) {
this.data1 = data1;
}
public String getData2() {
return data2;
}
public void setData2(String data2) {
this.data2 = data2;
}
public int getData3() {
return data3;
}
public void setData3(int data3) {
this.data3 = data3;
}
}
output is : 2017 2019 2020