HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

Searching through a contact list for given criteria

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
contactsearchingcriteriaforthroughlistgiven

Problem

I have been staring at this code for awhile now and I am thinking there is a way to optimize it (namely the if-else statement with the for-loops).

Additionally, this needs to be done with an array list as that is my assignment requirement. I have all my code working, and it is not due for a few days, so I am looking for ways to improve it while extending my learning beyond the classroom.

The numberOfContacts variable is fed into the method from the main method, which gets the count from another method that reads through a text file to get the number of contacts.

/**
 * search method searches through the contact list for a given criteria
 * and displays all results.
 * @param searchString is type String.
 * @param type is type String.
 * @param numberOfContacts is type int.
 * @param contacts is type Person[].
 */
public static void search(String searchString, String type, int numberOfContacts, Person[] contacts) {
    // Initialize variables for results
    int found = 0;
    int[] results = new int[numberOfContacts];

    // Determine the type of search
    if (type.equals("name")) {
        // Search by name
        for (int x = 0; x  0) {
        for (int x = 0; x < found; x++) {
            System.out.println(contacts[results[x]].getName() + "\t" + contacts[results[x]].getPhone());
        }
    }

    System.out.println("\n\n\n");
}

Solution

If you are limited to use only Arrays, you can create a interface like this

public static interface Checker {
    public boolean check(Person p, String searchString);
}


Create a Checker for every type of comparison you want.

And compare with the Checker

for (int x = 0; x < numberOfContacts; x++) {
    if (checker.check(contacts[x], searchString)) {
        results[found] = x;
        found++;
    }
}


You can see a working example here (with your classes and methos): http://ideone.com/2C6kei

Note:
With this method is easy to expand the search criteria (as you see in the example, with a anywhere Checker).

Code Snippets

public static interface Checker {
    public boolean check(Person p, String searchString);
}
for (int x = 0; x < numberOfContacts; x++) {
    if (checker.check(contacts[x], searchString)) {
        results[found] = x;
        found++;
    }
}

Context

StackExchange Code Review Q#31270, answer score: 2

Revisions (0)

No revisions yet.