简体   繁体   中英

How to search a string element in a class arraylist? (java)

My question is that there is a method printPetInfoByName() searches the list of pets for every pet of a given name, and prints the pet's information, using the toString() method. The arraylist is of type Pet and name is given from main method (i haven't coded it yet) I need to print info of a pet using toString() by searching arraylist. If the given name is present in list then it will print info.

my code looks like this 在此处输入图片说明

but it produces error > incompatible types: Pet cannot be converted to CharSequence for line 20 if i write for(String search:list) then it gives error that Pet cannot be converted to String for line 18

Use below code for your method:

public void printPetInfoByName(String name) {
    for (Pet search : list)
        if (search.getName().contains(name))
            search.toString(); //System.out.println(search.toString());
}

Define toString method in abstract class Pet .

String.contains checks if a substring is present in the string. It takes a CharSequence as parameter, and you are now giving it a Pet. That why you get the error.

I assume you have some kind of name field on your pets that you can access with a get method? Instead of checking whether or not the string contains the pet, consider asking if the pet's name is equal to the search string.

I think you should get your way working first. But if you are interested java 8 streams are a good tool when working with Collections. Here is how one could solve your problem using them:

list.stream()
            .filter(p -> p.getName().equals(name))
            .forEach(System.out::println);

list.stream() "starts" the stream.

filter filters all elements p where p's name is equal to the name you pass as an argument.

forEach does something for all elements in the stream. Note that by filtering it, the remaining elements are those we want.

字符串不能与复杂对象进行比较。它们不是同一类型,因此您的程序不知道如何使用它。

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