Skip to content

Latest commit

 

History

History
40 lines (29 loc) · 1.59 KB

7206.md

File metadata and controls

40 lines (29 loc) · 1.59 KB

Back to questions

Solution to 7206: Understanding references

See code at solutions/code/tutorialquestions/question7206

The main method in PrintBook.java prints:

New C++ book(ISBN: 1)
Haskell(ISBN: 2)

You might be surprised that it does not print:

New C++ book(ISBN: 1)
Haskell(ISBN: 2)
Java(ISBN: 1)

The reason this is not printed is as follows. When you add an object o to a Set s in Java, the Set implementation first checks whether s already contains an object that is equal to o. This check for equality is implemented using the equals method. Notice that in the Book class, equals has been implemented (i.e., the default equals method provided in the Object class has been overridden). A Book is deemed equal to another object if that object is also a Book, and if the books have equal ISBNs. Importantly books with the same ISBN are regarded as equal even if they have different titles. As a result, the line:

s.add(new Book(1, "Java"));

has no effect: set s already contains a book with ISBN 1, i.e. a book that is "equal" to new Book(1, "Java").

This question also illustrates the use of object references. The set s contains references to objects, not actual objects. Thus when reference b is added to s, the reference b and a reference in the set s both refer to the same Book object. After the call b.setTitle("New C++ book"), when we display all the books referred to by references contained in s, we see the new title.