Starting from:
$30

$24

Part 1 Prerequisite material

Objectives
    • Understanding when to use “==” or “equals”
    • Manipulating arrays and references
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)).
2 Manipulating arrays - FindAndReplace
Complete the implementation of the (static) class method String[] findAndReplace(String[] in, String[] what, String[] with) of the class Utils. The method returns a copy of the array in where each word occurring in the array what has been replaced by the word occurring at the corresponding position in the array with. The array designated by in must remain unchanged. If there are duplicate words in the array what, simply use the first instance you find.
Later in the semester, we will learn about exceptions. Exceptions provide tools for handling error situations. In the meantime, the method findAndReplace returns null whenever one of the preconditions of the methods is violated:
    • In particular, the formal parameters cannot be null.
    • For all three arrays, none of the elements can be null.
    • The query and replacement arrays must be of the same length.
You will hand this exercise in. Download and complete the starter file here: Utils.java.

More products