Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What can I store a single element in a Collection? [closed]

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);
    }
}
like image 807
Sara Avatar asked Jul 24 '15 07:07

Sara


2 Answers

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.

like image 98
2787184 Avatar answered Nov 03 '22 07:11

2787184


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.

like image 31
Florian Schaetz Avatar answered Nov 03 '22 05:11

Florian Schaetz