Unit 4 Day 18 Arraylist Object Methods
Share
Practice Question
public class Item
{
private String name;
private int price;
public Item(String n, int p) { name = n; price = p; }
public String getName() { return name; }
public int getPrice() { return price; }
}
// In another class:
ArrayList<Item> cart = new ArrayList<>();
Item book1 = new Item("Java Guide", 30);
Item book2 = new Item("Java Guide", 30);
cart.add(book1);
System.out.println(cart.contains(book1)); // Statement I
System.out.println(cart.contains(book2)); // Statement II
System.out.println(cart.indexOf(book2)); // Statement III
Step-by-Step Trace
// book1 and book2 are different objects in memory
// Even though they have the same name and price,
// they are NOT the same reference
// Statement I: cart.contains(book1)
// Checks: is book1 == book1? YES (same reference)
// Prints: true
// Statement II: cart.contains(book2)
// Checks: is book1 == book2? NO (different references)
// Item class has no equals() method, so == is used
// Prints: false
// Statement III: cart.indexOf(book2)
// Searches for book2 using == comparison
// book1 == book2 is false, so not found
// Returns: -1 (negative = not found)
Key Concept
Object Identity vs Equality: By default, Java compares objects using == (same memory address). Two objects with identical field values are still "not equal" unless the class overrides the equals() method.
ArrayList methods affected: contains(), indexOf(), remove(Object), and lastIndexOf() all use equals() for comparison. Without an override, they fall back to == reference comparison.
Common Mistakes
book1 and book2 have the same name and price, but they are separate objects created with separate "new" calls. Without overriding equals(), they are compared by reference, not content.
indexOf() returns -1 when the object is not found. Since book2 is not == to any element in the list, it returns -1, which is negative (not found).
On the AP exam, assume classes do NOT override equals() unless explicitly stated. This means contains(), indexOf(), and remove(Object) compare references, not field values.
Want More Practice?
Master AP CSA with guided practice and expert help
Schedule 1-on-1 Tutoring Practice FRQs