0

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.

asked Feb 28, 2014 at 5:22
2
  • Have u overridden equals and hascode methods in Contact class ?? and is it implements comparable or comparator interface ?? Commented 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? Commented Feb 28, 2014 at 5:29

1 Answer 1

2

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.

answered Feb 28, 2014 at 5:29
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.