0

Anyone know the answer to this question? studying for an exam atm and it looks like this is coming up.

 b) Amend the Person class so the code snippet below will work properly
 ArrayList<Person> people = new ArrayList<Person>();

 //Assume Person objects have been added to the list

 if (people.contains(new Person("Adam Ant", 48)))
 {
 //Do something
 }
 else
 {
 //Do something else
 } 
Shay
  • 1
  • First you need to provide everything you have, including the Person class, then we can start helping you, but the general idea is that you need to implement/override the compareTo() method – Vilsol Jan 12 '16 at 23:59
  • 1
    Have you consider how `people` knows if it contains a particular object? How that comparison might work? – MadProgrammer Jan 12 '16 at 23:59
  • read the doc. here: https://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html#contains(java.lang.Object) – njzk2 Jan 13 '16 at 00:01

1 Answers1

1

Amend the Person class so the code snippet below will work properly

Override Object.equals(Object) in Person. Something like,

@Override
public boolean equals(Object obj) {
    if (obj instanceof Person) {
        Person p = (Person) obj;
        return this.name.equals(p.name) && this.age == p.age;
    }
    return false;
}

It's also a good practice to override hashCode (or your Person won't work correctly with some Collections). Something like,

@Override
public int hashCode() {
    return name.hashCode() + age;
}
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249