Method equals and the interface

$24.99 $18.99

Learning Objectives Create your own method equals(Object o) Implement a parametrized interface Use the interface java.util.Comparator<T> Section 1: the method equals As you know, the class Object defines a method equals. public class Object { // … public boolean equals(Object obj) { return this == other; } } Since in Java, every class inherits from the class Object, every class inherits the method boolean equals(Object obj).…

5/5 – (3 votes)

You’ll get a: zip file solution

 

Categorys:

Description

5/5 – (3 votes)

Learning Objectives

  • Create your own method equals(Object o)

  • Implement a parametrized interface

  • Use the interface java.util.Comparator<T>

Section 1: the method equals

As you know, the class Object defines a method equals.

public class Object {     // ...     public boolean equals(Object obj) {         return this == other;     } }

Since in Java, every class inherits from the class Object, every class inherits the method boolean equals(Object obj). This is true for the predefined classes, such as String and Integer, but also for any class that you will define.

The method equals is used to compare references variables. Consider two references, a and b, and the designated objects.

  • If you need to compare the identity of two objects (do a and b designate the same object?), use “==” (i.e. a == b );

  • If you need to compare the content of two objects (is the content of the two objects the same?), use the method “equals” (i.e. a.equals(b)).

In this first part, we are going to create a simple class Book. This class is quite minimal. It contains the following:

  • An instance variable author of type String;

  • An instance variable title of type String;

  • An instance variable year of type int (the publication year of that book);

  • A contructor Book(String author, String title, int year), which receives that new instance’s author, title and publication year as paramters;

  • A method toString(), which returns a String representation of that instance, using the format “author: title (year)“;

  • A method equals(Object o).

We want our implementation to be as robust as possible. In particular, the method equals should handle every particular case you can think about. Make sure your code passes all the provided JUnit tests.

Method equals and the interface
$24.99 $18.99