Linear Search

  • Understand linear search well enough to implement it

Here is a simple strategy to implement the find method: go over elements of the students array in sequence till the desired element (student with the given email) is found, or search space is exhausted (that is, we checked all the students and we have not found the target). This strategy is called linear search.

Exercise Implement find according to the linear search strategy.

Solution
// Assumption: students' emails are unique.
public Student find(String email) {
    for (int i = 0; i < numStudents; i++) {
        if (email.equals(students[i].getEmail())) {
            return students[i];
        }
    }
    return null;
}

Notice I've used .equals to compare two strings (and not ==). Generally speaking, you should not use == for non-primitive types because with ==, you are comparing memory locations on objects, not their values.

Aside: see Equality and Comparison in Java: Pitfalls and Best Practices).

Resources