UndisclosedCurtain
UndisclosedCurtain

Reputation: 171

Are these two ways of adding equivalent?

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

Answers (1)

Stephen C
Stephen C

Reputation: 718826

The two approaches give different results.

Version 1.

public boolean addSeating(Group group) {
    return seatings.add(createSeating(group));
}

This will:

  1. return true if the newly created seating was added to the collection
  2. return false if the new created seating was NOT added to the collection

Note 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.)

Version 2.

public boolean addSeating(Group group) {
    Seating seating = createSeating(group);
    if (seating != null){
        seatings.add(seating);
        return true;
    }
    return false;
}

This will:

  1. return false if the newly created seating is null
  2. otherwise return true

Note that the true result happens irrespective of whether a new seating was added.

Upvotes: 2

Related Questions