简体   繁体   中英

How to search for String that has more than one word in ArrayList?

My search method works fine for one word strings, but not for two words or more.

I am supposed to check to see if the titleToFind matches a DVD title in the

ArrayList<DVD>DVDlist

My search method:

public DVD search(String titleToFind) {
    for (DVD dvdEntry : DVDlist) {
        if (dvdEntry.GetTitle().equalsIgnoreCase(titleToFind)) {
            return dvdEntry;
        }
    }
    return null;
}

I am not sure how to approach this problem.

Your main problem is that you stop searching when you hit your first match (the return statement in the loop). Below is an example of returning a list containing all the matches.

If you are not allowed to use a list, you could return an int (number of matches) or csv of matches.

public List<DVD> search(String titleToFind) {
    List<DVD> matches = new ArrayList<DVD>();    
    for (DVD dvdEntry : DVDlist) {
        if (dvdEntry.GetTitle().equalsIgnoreCase(titleToFind)) {
            matches.add(dvdEntry);
        }
    }

    return matches;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM