KotlinCS 124 LogoJava
PrevIndexNext
Kotlin
Java
  • Equality and Object Copying : 10/08/2026

  • Polymorphism : 10/07/2026

  • Inheritance : 10/06/2026

  • Data Modeling 1 : 10/05/2026

  • Static : 10/02/2026

  • Encapsulation : 10/01/2026

  • Constructors : 09/30/2026

  • Objects, Continued : 09/29/2026

  • Introduction to Objects : 09/28/2026

  • Testing and Compilation : 09/25/2026

  • Practice with Collections : 09/24/2026

  • Maps and Sets : 09/23/2026

  • Lists and Type Parameters : 09/22/2026

  • Imports and Libraries : 09/21/2026

  • Multidimensional Arrays : 09/18/2026

  • Practice with Strings : 09/17/2026

  • null : 09/16/2026

  • Algorithms and Strings : 09/15/2026

  • Strings : 09/14/2026

  • Functions and Algorithms : 09/11/2026

  • Practice with Functions : 09/10/2026

  • More About Functions : 09/09/2026

  • Errors and Debugging : 09/08/2026

  • Functions : 09/04/2026

  • Practice with Loops and Algorithms : 09/03/2026

  • Algorithms : 09/02/2026

  • Loops : 09/01/2026

  • Arrays : 08/31/2026

  • Compound Conditionals : 08/28/2026

  • Conditional Expressions and Statements : 08/27/2026

  • Operations on Variables : 08/26/2026

  • Variables and Types : 08/25/2026

  • Welcome to CS 124 : 08/24/2026

Equality and Object Copying

public class Person {
private String name;
Person(String setName) {
name = setName;
}
public boolean equals(Object o) {
if (o == null || !(o instanceof Person other)) {
return false;
}
return name.equals(other.name);
}
}
Person first = new Person("Me");
Person second = new Person("You");
System.out.println(first.equals(second));

I’m glad you’re back. The last few lessons were heavy, so in this one we’re going to slow down and integrate. We’ll discuss object equality and how to make object copies. While these are new, they are largely straightforward applications of things that we already know.

Warm Up Test Correctness Challenge
Warm Up Test Correctness Challenge

But first, let’s warm up with another graded test correctness challenge!

Completing this one requires a new testing pattern that we haven’t yet seen: how to test that a method correctly asserts. So let’s start by demonstrating how to do that.

void shouldCheckNull(String input) {
assert input != null;
}
void test() {
shouldCheckNull(null);
}
test();

Also note that you may want to use the Map.of Java method to create maps for your testing function. It accepts pairs of values that represent mappings and loads the Map appropriately:

import java.util.Map;
Map<String, Integer> values = Map.of("test", 4, "me", 2);
System.out.println(values);
Created By: Geoffrey Challen
/ Version: 2026.10.0

Given a String containing words separated by the " " (space) character, write a method wordLengths that return a Map<String, Integer> mapping each word that is contained in the String to its length. assert that the passed String is not null.

So, for example, given the String "Wow that is amazing", you would return a map with four mappings: "Wow" to 3, "that" to 4, "is" to 2, and "amazing" to 7.

Note that you should not add any import statements, since both java.util.Map and java.util.HashMap are already available.

Test Correctness Challenge

Your challenge is to write tests for the problem described above.

  • Provide a method named test that accepts no arguments and does not return a value.
  • If the implementation of the method described above is incorrect, your test method should fail an assertion.
  • If it is correct, do not fail an assertion.
  • You will want to use Java's assert method
  • Your test code should not use loops or define extra methods.

Equality
Equality

What does it mean for two things to be the same? On one hand this is a deep epistemological question. But in our computer programs, it has practical importance.

For example, I might have a list of items and want to remove all of the duplicates, or find something. I might require a key of some kind to access some information, and need to be able to tell whether the key you present is the same as the one that is required. These are examples of places in computer code where equality matters.

Java’s notion of equality is left up to us, the class designer, to define. Let’s look at an example of how.

public class Pet {
}

Object.equals
Object.equals

equals is one of the methods defined by Object. That means, if we don’t override equals, our classes inherit the equals method defined by Object. This doesn’t do nothing, but it’s not particularly useful. Let’s see how it works:

public class Student { }

Practice: Solve Course Equality

Created By: Geoffrey Challen
/ Version: 2020.9.0

Create a public class named Course. Course should define a single public constructor that accepts three fields: a String (the department), a String (the course number, and yes, this must be a String) and an int (the enrollment). You are welcome to name these fields however you like! Your constructor should reject null departments and numbers and negative enrollments.

You do not need to provide any getters and setters! Instead, define a single method named equals. Your equals method accepts an Object as a single parameter. It should return true if the passed object is a Course and has the same values for the department and number, and false otherwise.

Copying Java Objects
Copying Java Objects

It may surprise you to learn that Java has no built-in way to copy an object. Object does provide a clone method, but even the Java architects themselves recommend against it.

The reasons for this are somewhat out of scope for us at this point. Put simply, objects may have complex internal state that is difficult or impossible to copy. Put another way, not every object may represent something that can be copied.

However, when our objects can be copied we can enable this using a pattern called a copy constructor. Let’s look at how to do that together:

public class Student { }

Java Records
Java Records

Before we finish this lesson, I want to introduce you to a new(ish) Java feature which was released in Java 16. However, it’s really exciting, and provides a much simpler way of working with classes.

public class Person {
private final String name;
private final double age;
Person(String setName, double setAge) {
name = setName;
age = setAge;
}
public String getName() {
return name;
}
public double getAge() {
return age;
}
public boolean equals(Object o) {
if (o == null || !(o instanceof Person other)) {
return false;
}
return name.equals(other.name) && age == other.age;
}
}

Practice: Solve Restaurant Equality

Created By: Geoffrey Challen
/ Version: 2021.9.0

Create a public class named Restaurant. Restaurant should define a single public constructor that accepts three fields: a String (the name), a String (the type of cuisine) and an int (the capacity). You are welcome to name these fields however you like! Your constructor should reject null names and cuisines and negative or zero capacities.

You do not need to provide any getters and setters! Instead, define a single method named equals. Your equals method accepts an Object as a single parameter. It should return true if the passed object is a Restaurant and has the same values for the name and cuisine, and false otherwise.

Homework: Solve Location Equality

Created By: Geoffrey Challen
/ Version: 2022.9.0

Create a public class named Location. Location should define a single public constructor that accepts three fields: a String (the description), and a latitude and longitude position, as double values, in that order. You are welcome to name these fields however you like! Your constructor should reject null descriptions and invalid latitude and longitude values. Valid longitude values are between -180.0 and 180.0, inclusive, while valid latitude values are between -90.0 and 90.0, inclusive.

You do not need to provide any getters and setters! Instead, define a single method named equals. Your equals method accepts an Object as a single parameter. It should return true if the passed object is a Location and has the same position as the passed object, and false otherwise.

CS People: James Mickens
CS People: James Mickens

James Mickens is a Harvard professor who does work on distributed systems and large-scale web services. He’s had papers published in the most prestigious venues in systems and networking, and received tenure at Harvard in 2019(1).

James is also funny. Very funny! You can find his technology-driven humor in written form, but at least I think he’s at his best when giving a talk. Here’s one brief example, that also touches on an important issue:

(And if you have more time, this longer talk is a personal favorite.)

More Practice

Need more practice? Head over to the practice page.