I am creating a program that allows the user to enter the name of a contact to search for. If the contact is found, then the contact's other info (phone number and email) will be displayed.
My ArrayList looks like this:
ArrayList<Contact> contacts = new ArrayList<Contact>();
contacts.add(new Contact("Patrick McGee", "334-555-8860", "[email protected]"));
contacts.add(new Contact("John Appleseed", "142-555-6740", "[email protected]"));
contacts.add(new Contact("Matt Jordan", "213-555-2323", "[email protected]"));
contacts.add(new Contact("Kanye East", "255-434-9909", "[email protected]"));
contacts.add(new Contact("Derrick Flower", "144-555-1111", "[email protected]"));
I have variables: String name, String num, and String email.
Again, the user is asked to input the name (the first string of the arraylist).
If the name is found, then the contact will be printed (with all info). I have tried using BinarySearch in Collections, but that gave me errors that were very confusing. If more info is needed, feel free to ask.
Is there a method in searching like this? Thanks.
-
Have u overridden equals and hascode methods in Contact class ?? and is it implements comparable or comparator interface ??Naren– Naren2014年02月28日 05:27:03 +00:00Commented Feb 28, 2014 at 5:27
-
I tried to use implements comparator, but got plenty of errors. Can you show me an example of how I can use the Comparator in this situation?pmcg521– pmcg5212014年02月28日 05:29:18 +00:00Commented Feb 28, 2014 at 5:29
1 Answer 1
Nope, there's not a method that does this. You have to do it yourself because here you're only checking for a single property.
for(Contact contact : contacts) {
if(contact.getName().equals(nameToSearchFor)) {
// return the contact, print it or whatever you need
}
}
There are some things like Comparable and equals that the API uses for this type of thing but an implementation that only considered the name would break their contracts.
It would be possible to define a Comparator that only looked at the name and use binarySearch but that would require:
- Contact to implement Comparable otherwise
- The list to be sorted
And to be honest there's not much to gain by doing those things in this case.