I need to get List<Example>
from the object, add an element to it, and attach the modified list to the object. Is there a wise way to do it in one line? Right now it looks like the following:
List<Example> examples = user.getExamples();
examples.add(example);
user.setExamples(examples);
I thought about smth like this:
user.setExamples(user.getExamples().add(example));
but it does not work due to that
add
returns true
In object-oriented programming, you should think in terms of asking an object to "do its thing" rather than you trying to manipulate its innards from outside.
So rather than extract, manipulate, and re-inject, simply ask that object to add an item. You don't even know if there is a list inside that object. Let the object take care of tracking items as it sees fit.
user.addExample( myExample ) ;
In other words, having getters and setters is often a sign of poor object-oriented design.
If you insist on external modifications:
List#add
on the object returned by the getter. I would add an if
test to verify you got back true
, as a false
means the addition failed.To use the setter, you must make multiple statements.
List< Example > list = user.getExamples() ;
if( list.add( myExample ) )
{
user.setExamples( list ) ;
} else
{
… handle failure …
}
If that returned list is not modifiable, you'll need to make a new one. Pass the unmodifiable list to the constructor.
List< Example > list = new ArrayList<>( user.getExamples() ) ;
if( list.add( myExample ) )
{
user.setExamples( list ) ;
} else
{
… handle failure …
}