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
 } 
3
  • 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 Commented Jan 12, 2016 at 23:59
  • 1
    Have you consider how people knows if it contains a particular object? How that comparison might work? Commented Jan 12, 2016 at 23:59
  • read the doc. here: docs.oracle.com/javase/7/docs/api/java/util/… Commented Jan 13, 2016 at 0:01

1 Answer 1

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;
}
Sign up to request clarification or add additional context in comments.

2 Comments

Should always override hashCode when you do it for equals; see Joshua Bloch "Effective Java".
@duffymo Good advice. Edited.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.