Skip to main content

Section 5.3 Growth Level

Subsection 5.3.1 Instructions

The following program requires you to write a method to locate duplicates within an ArrayList containing Animal objects. A "duplicate" refers to an Animal with the same name as another Animal that is already in the list. That is, if an Animal with a particular name already exists in the ArrayList, any subsequent Animal with the exact same name is considered a duplicate.
public class Animal {
  //**TO-DO: Initialize a static ArrayList here called allAnimals**
  String name;
  String type;

  public Animal(String name, String type){
      this.name = name;
      this.type = type;
      allAnimals.add(this);
  }

  public String toString(){
      return name + " (" + type + ")";
  }

  //**TO-DO: Write method that checks if an animal in the list**
  public static boolean isDuplicate(String nameToCheck){
  
  }
}
The program contains a class named Animal, where each instance represents an individual animal that is characterized by a name and a type. Each animal that is created is added to a static ArrayList allAnimals. You may assume that all names begin with a capital letter.
The expected output is:
DUPLICATE: There is already an animal with the name "Alice" in the list: Alice (aardvark)
UNIQUE: The name George is unique.
UNIQUE: The name Timothy is unique.
DUPLICATE: There is already an animal with the name "Paul" in the list: Paul (piranha)
DUPLICATE: There is already an animal with the name "Orville" in the list: Orville (ostrich)
UNIQUE: The name Oliver is unique.
You have attempted of activities on this page.