Reputation: 171
I am currently cramming for an exam in Java, and I was wondering if the two following approaches yields the same result apart from the null check? And if not, why?
Seatings is a collection,
public boolean addSeating(Group group) {
//return seatings.add(createSeating(group));
Seating seating = createSeating(group);
if (seating != null){
seatings.add(seating);
return true;
}
return false;
Upvotes: 0
Views: 130
Reputation: 718826
The two approaches give different results.
public boolean addSeating(Group group) {
return seatings.add(createSeating(group));
}
This will:
true
if the newly created seating was added to the collectionfalse
if the new created seating was NOT added to the collectionNote that we do not know if seatings
is a List
or a Set
or some other kind of collection:
If seatings
is a Set
, then add
will return false
in the case that the element being added is already in the set. (Or more precisely if it is equal to and element already in the set.)
Other collection types may refuse the add
for other reasons. For example, a List
class could refuse to add an element that was null
or had the wrong type, or it could refuse the add if the list is "full" ... in some sense.
(If seatings
is ArrayList
, then the add
will always succeed, so the result will always be true
.)
public boolean addSeating(Group group) {
Seating seating = createSeating(group);
if (seating != null){
seatings.add(seating);
return true;
}
return false;
}
This will:
false
if the newly created seating is null
true
Note that the true
result happens irrespective of whether a new seating was added.
Upvotes: 2