Reputation: 323
I have a java class which has a List as following:
public class TestEntity {
private String name;
private List<DataEntry> dataEntries;
}
class DataEntry {
private String para1;
private String para2;
private String para3;
}
How could i add a DataEntry's instance into a TestEntity's instance?
Upvotes: 0
Views: 1740
Reputation: 140457
First you need to ensure that your list is actually not null, like:
private final List<DataEntry> entries = new ArrayList<>();
and then you can do something like
entries.add(new DataEntry());
or probably more useful:
DataEntry entry = new DataEntry();
entry.para1 = ...
entries.add(entry);
Of course, the more realistic thing would be to add a custom constructor to the DataEntry class, so that you can pass the required arguments via the constructor.
Or, you add a method
void addEntry(DataEntry entry) {
entries.add(entry);
to your TestEntity
class.
Upvotes: 2
Reputation: 69440
There are two possiblities:
First: You add a constructor to add an entry:
public class TestEntity {
private String name;
private List<DataEntry> dataEntries;
public TestEntity (String name,DataEntry entry){
this.name = Name;
this.dataEntry = new ArrayList<>();
this.dataEntry.add(entry)
}
}
Second: You add an addDataEntry
function:
public class TestEntity {
private String name;
private List<DataEntry> dataEntries;
public void addDataEntry(DataEntry entry){
if (this.dataEntry == null){
this.dataEntry = new ArrayList<>();
}
this.dataEntry.add(entry)
}
}
Upvotes: 1
Reputation: 171
Pretty simple if you just instantiate it.
dataEntries.add(new DataEntry());
Upvotes: 1