Reputation: 105
I don't really understand what parameters I should pass to the contains() method. I have my own class called Name which consists of 2 strings (firstName, secondName). I have created an ArrayList of type Name and 2 Name objects of the same name e.g. ("Joe, "Bloggs") 2x. So what paremeters do I have to pass to check whether it works. I have correctly overriden the equals method for Name class. This is my main program:
import java.util.ArrayList;
public class EqualsTest {
public static void main(String[] args) {
ArrayList<Name> names = new ArrayList<Name>();
names.add(new Name("Joe", "Bloggs"));
names.add(new Name("John", "Smith")); //<--
names.add(new Name("Alan", "Wake")); // | the same name
names.add(new Name("Robert", "High"));// |
names.add(new Name("John", "Smith")); //---
names.contains(Name("Joe", "Bloggs"));
}
}
Upvotes: 1
Views: 207
Reputation: 35577
You can use
names.contains(new Name("Joe", "Bloggs"));
But you should override equals()
method in Name class to work it as expected.
When ever you need to deal with collection frame work in Java
, better to override both equals()
and hashCode()
method in your classes else you end up with mess.
Upvotes: 2
Reputation: 393936
Assuming you've overridden equals
correctly in your Name
class, it should be:
if (names.contains(new Name("Joe", "Bloggs"))) {
...
}
Upvotes: 7