0

I have three classes in my program: Person, Main, and SearchTool. I have an ArrayList of Person objects inside my Main class called personList. I am trying to use a method in SearchTool called search() to find a Person object inside personList.

Here is my search() method inside the SearchTool class:

public T search(T target, ArrayList<T> list) {
        for (int x = 0; x < list.length(); x++) {
            T obj = list.get(x);
            if (obj.equals(target)) {
                return obj;
            }
        }
        return null;
    }

Here is the driver code I have been testing this method with:

SearchTool<Person> searchTool = new SearchTool<Person>();
Person target = new Person("a", 5);
Person result = searchTool.search(target, list);
System.out.println(result);

However when I do this all that I get is null. I do have a toString() inside my Person class that prints the name and age, by the way. Please help me, I am very stuck here and nothing I try seems to work.

Edit: as per request, here is my Person class. I have removed the get and set methods for ease of reading.

package testing;

public class Person implements Comparable<Person> {
    private String name;
    private int age;
    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }
    public Person(Person p) {
        this(p.name, p.age);
    }
    public boolean equals(Person p) {
        if (this.getName().equals(p.getName()) && this.getAge() == p.getAge()) {
            return true;
        }
        else {
            return false;
        }
    }
    @Override
    public int compareTo(Person p) {
        return this.name.compareTo(p.name);
    }
    public String toString() {
        return "Name: " + name + "\nAge: " + age + "\n\n";
    }   
}

Edit: it seems like I did not override the Object class by referring to a Person object in my equals() method. I have corrected this by adding an Object as a parameter and casting it to Person. Thank you everyone for your help.

Ben Foley
  • 21
  • 4

0 Answers0