Arrays of objects and equals

An array holds values of one type, and a class is a type, so an array of objects holds references to objects. The array itself knows only the references: an element may be null, two elements may point at one object, and comparing two elements compares references unless the class says otherwise.

An array of objects

The program below declares a Book class next to the public class, which is legal because only the public class has to match the file name. The array has three slots, two objects and one null.

The file Objects.java:

public class Objects { public static void main(String[] args) { Book[] books = new Book[3]; books[0] = new Book("Dune", 412); books[1] = null; books[2] = new Book("Emma", 474); for (Book book : books) { if (book == null) { System.out.println("empty slot"); } else { System.out.println(book.getTitle() + ": " + book.getPages()); } } System.out.println("filled: " + count(books)); } static int count(Book[] books) { int filled = 0; for (Book book : books) { if (book != null) { filled++; } } return filled; } } class Book { private final String title; private final int pages; Book(String title, int pages) { this.title = title; this.pages = pages; } String getTitle() { return title; } int getPages() { return pages; } }

javac -Xlint:all Objects.java
java Objects

Dune: 412
empty slot
Emma: 474
filled: 2

The loop prints the two books and names the empty slot. Without the null check, book.getTitle() on the empty slot would throw NullPointerException and stop the loop at the second element.

Null elements

A new array of a reference type is a row of nulls, and an element stays null until something is assigned to it. That is a useful state, and it is not an object: every method call on it fails, every field read fails, and == against null is the only test that works.

A program that builds an array in a loop and leaves a slot empty has two choices: fill the array exactly, or treat null as an error and check it at the point of use. The second is the reason a method that takes an array documents whether null elements are allowed.

equals on an array of objects

Two references to the same object are equal with ==. Two objects with the same fields are not, unless the class overrides equals. The class below does, and the search through the array uses it.

import java.util.Objects; public class EqualsArray { public static void main(String[] args) { Item a = new Item("pen", 2); Item b = new Item("pen", 2); System.out.println("==: " + (a == b)); System.out.println("equals: " + a.equals(b)); Item[] items = {a, new Item("book", 10)}; System.out.println("contains pen: " + contains(items, new Item("pen", 2))); System.out.println("contains lamp: " + contains(items, new Item("lamp", 5))); } static boolean contains(Item[] items, Item target) { for (Item item : items) { if (item.equals(target)) { return true; } } return false; } } class Item { private final String name; private final int price; Item(String name, int price) { this.name = name; this.price = price; } @Override public boolean equals(Object other) { if (!(other instanceof Item)) { return false; } Item item = (Item) other; return name.equals(item.name) && price == item.price; } @Override public int hashCode() { return Objects.hash(name, price); } @Override public String toString() { return name + " (" + price + ")"; } }

javac -Xlint:all EqualsArray.java
java EqualsArray

==: false
equals: true
contains pen: true
contains lamp: false

The new Item in the search is a third object, and the search still finds the first one because equals compares the fields. Without the override the search would compare references and always answer false for a freshly built target.

The equals contract

An equals override must be reflexive, symmetric, transitive and consistent, and it must return false for null. It must also have a matching hashCode, because a collection uses the hash to find the object before it calls equals: two equal objects with different hash codes are two objects to a HashSet.

Objects.equals and Objects.hash do the null-safe parts of both methods. A record does all of it without a line of code, which is why the next part of the course uses records for the small value classes.

Exercises

  1. Add a fourth book to Objects.java and predict the printed filled count.
  2. Point books[1] at the same object as books[0] and run the program again. How many objects are in the array?
  3. Remove the null check from the loop and run the program. Which exception and which line?
  4. Add a field to Item, update equals and hashCode, and check that the search still finds the pen.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What does a new array of a reference type contain?

    Answer

    null in every element

    The default of a reference is null, and an object exists only after it is created and assigned.

  2. What happens when a method is called on a null element?

    Answer

    NullPointerException

    A method call needs an object, and null is the absence of one.

  3. When are two objects equal with ==?

    Answer

    When they are the same object

    For references == compares identity; content equality needs equals.

  4. What does this program print? public class Q1 { public static void main(String[] args) { String[] names = new String[3]; System.out.println(names[0]); } }

    Answer

    null

    A new String array holds null in every element, and println prints the word null.

  5. What does this program print? public class Q2 { public static void main(String[] args) { int[] values = {1, 2, 3}; int[] copy = values; copy[0] = 9; System.out.println(values[0] + " " + (values == copy)); } }

    Answer

    9 true

    The assignment copies the reference, so both names point at one array and == is true.

  6. What does this program print? public class Q3 { public static void main(String[] args) { String a = new String("x"); String b = new String("x"); System.out.println(a.equals(b) + " " + (a == b)); } }

    Answer

    true false

    String overrides equals to compare characters, while == compares the two references.

  7. What does this program print? public class Q4 { public static void main(String[] args) { String[] names = {"Ada", null, "Alan"}; int filled = 0; for (String name : names) { if (name != null) { filled++; } } System.out.println(filled); } }

    Answer

    2

    The null element is skipped, so two of the three slots are counted.

  8. What does this program print? public class Q5 { public static void main(String[] args) { int[][] grid = new int[2][]; System.out.println(grid[0] == null); } }

    Answer

    true

    new int[2][] creates the outer array with null rows, and no inner array exists yet.

  9. Why must an equals override be paired with hashCode?

    Answer

    A hash collection finds equal objects by hash before it compares them

    Two equal objects must have the same hash, or a HashMap or HashSet looks in the wrong bucket.

  10. What does this program print? public class Q6 { public static void main(String[] args) { String[] names = {"Ada", "Alan"}; for (String name : names) { System.out.print(name.toUpperCase().charAt(0)); } System.out.println(); } }

    Answer

    AA

    Each name is upper-cased and its first character printed without a separator, so the two letters are AA.

The code on this page was built with OpenJDK 21.0.13 (javac and java) and run on Alpine Linux in a Docker container.

Article author: Arthur Isaev