简体   繁体   English

如何在类arraylist中搜索字符串元素? (Java)的

[英]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. 我的问题是,有一个方法printPetInfoByName()在宠物列表中搜索给定名称的每个宠物,并使用toString()方法打印宠物的信息。 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. arraylist的类型为Pet,其名称是通过main方法指定的(我尚未对其进行编码)我需要通过搜索arraylist使用toString()打印宠物的信息。 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 但是它会产生错误>不兼容的类型:如果我写了(String search:list),则Pet不能转换为第20行的CharSequence,那么它给出的错误是Pet不能转换为第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 . 在抽象类Pet中定义toString方法。

String.contains checks if a substring is present in the string. String.contains检查字符串中是否存在子字符串。 It takes a CharSequence as parameter, and you are now giving it a Pet. 它以CharSequence作为参数,现在您给它一个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? 我假设您的宠物上有某种名称字段,可以使用get方法访问该字段? 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. 但是,如果您有兴趣,在使用Collections时,java 8流是一个很好的工具。 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. list.stream() “启动”流。

filter filters all elements p where p's name is equal to the name you pass as an argument. filter器过滤所有元素p,其中p的名称等于您作为参数传递的名称。

forEach does something for all elements in the stream. forEach对流中的所有元素执行操作。 Note that by filtering it, the remaining elements are those we want. 请注意,通过过滤它,剩下的元素就是我们想要的那些元素。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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