pmcg521
pmcg521

Reputation: 349

(Java) Searching ArrayList of Strings

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.

Upvotes: 0

Views: 345

Answers (1)

Radiodef
Radiodef

Reputation: 37835

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.

Upvotes: 2

Related Questions