I've got a DTO object used to get data from my server. It can be used for one or several elements. This DTO encapsulate a Collection
containing the data.
When my DTO brings me only one element, how should I store it?
Sample code:
public class DataDTO implements Serializable
{
private Collection<Data> data;
public DataDTO()
{
}
public Collection<Data> getData()
{
return data;
}
public void setData(Collection<Data> data)
{
this.data = data;
}
public void setData(Data singleData)
{
// At this time I use an ArrayList initialized with a capacity of 1
this.data = new ArrayList<Data>(1);
this.data.add(singleData);
}
}
You can use singleton methods from Collections class.
singletonList : Returns an immutable list containing only the specified object. The returned list is serializable.
singleton : Returns an immutable set containing only the specified object. The returned set is serializable.
singletonMap : Returns an immutable map, mapping only the specified key to the specified value. The returned map is serializable.
The question is, what do you want to do later with it? Is there a chance that you migh add another element? If not, you could use
this.data = Collections.singletonList( singleData );
If there is a chance that you might want to add elements later, then it's the typical question what List implementation to use, ArrayList is fine for many cases.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With