how to set up search method in java

Viewed 101

I’m new to Java and I’m trying to make a method called searchListBySurName that accepts a String argument and returns true or false depending on whether a name exists with that respective last name.

Here is what I have so far:


public boolean searchListBySurName(String SurName)

{
    if (list.contains(SurName)) {

        return true;
    } else {
        return false;
    }
}

Here is the test data I’m using to test the method:

public void testSearchListBySurName() {
  r.addName(new Name("Joe", "Bloggs"));
  r.addName(new Name("Fred", "Jones"));

  assertTrue("First search should find Jones, i.e. return true", r.searchListBySurName(new String("Jones")));

  r = new Register();
  r.addName(new Name("Joe", "Bloggs"));
  r.addName(new Name("Fred", "Wayne"));

  assertFalse("Second search should not find Jones, i.e. return false", r.searchListBySurName(new String("Jones")));
}

But, the test keeps coming back as failed. What mistake am I making and how can I fix it?

2 Answers

Your list is of Name, but you search for String, so it won't work. The straight-forward way is with a for loop:

public boolean searchListBySurname(String surname) {
    for (Name name : list)
        if (name.getSurname().equals(surname))
            return true;

    return false;
}

Or you could use Java 8 streams:

public boolean searchListBySurname(String surname) {
    return list.stream().anyMatch(name -> name.getSurname().equals(surname));
}

P.S. Also pay attention to method and parameter names.

It is ok to use list.contains() method. But you need to override the equals method of Name Class.

Using the List.contains(Object object) method to determine whether the ArrayList contains an element object (for this case where the SurName value of the Name is the same) should override the equals() method. If the equals() method in the element Object of List<E> is not override, it will cause the contains() method to always return false.

@Override  
public boolean equals(Name o) {  
    if (this.SurName = o.SurName){
        return true;
    } else{
        return false;
    }
}  

In method searchListBySurName:

public boolean searchListBySurName(Name name)

{
    if (list.contains(name)) {
        return true;
    } else {
        return false;
    }
}

And Use it like this:

public void testSearchListBySurName() {
  r.addName(new Name("Joe", "Bloggs"));
  r.addName(new Name("Fred", "Jones"));

  assertTrue("First search should find Jones, i.e. return true", r.searchListBySurName(new Name("","Jones")));

  r = new Register();
  r.addName(new Name("Joe", "Bloggs"));
  r.addName(new Name("Fred", "Wayne"));

  assertFalse("Second search should not find Jones, i.e. return false", r.searchListBySurName(new Name("","Jones")));
}
Related