【问题标题】:search is not working in Arraylist due to case sensitivity由于区分大小写,搜索在 Arraylist 中不起作用
【发布时间】:2023-01-31 21:20:18
【问题描述】:
  • 我创建了一个地址班级*
public class Address {
    
    
    private long id;
    private String organizationName;
    private long entId;
    private String orgAddress;
    private String orgType;

    }

我有创建了一个列表里面有 Address 对象,我创建了一个原料药使用它。

List<Address> list;
    
    
    
    public AddressServiceImpl() {
        list=new ArrayList<>();
        list.add(new Address(1,"Anth",123456,"Time square,NY","Doctor"));
        list.add(new Address(2,"carl",12114,"street 16,NY","Staff"));
    }

现在我需要搜索字符串的一部分现在从列表中,我想获取具有 **organizationName ** 作为相关字符串的对象

@Override
    public List<Address> searchAddress(String search) { 
        
        List<Address> listClone= new ArrayList<>();
        for(Address d : list){
            if(d.getOrganizationName().toLowerCase() != null && d.getOrganizationName().contains(search.toLowerCase())) {
               listClone.add(d);
        }
            
            
        }
        return listClone;
    

    }

但是当我搜索“Anth”和“anth”它没有给出任何回应。请帮忙!!!

但是当我搜索“Anth”和“anth”它没有给出任何回应。请帮忙!!!

【问题讨论】:

  • 你应该首先看看你当前的代码: if ( d.getOrganizationName().toLowerCase() != null ... ) -> 你能发现这里的严重问题吗?该行不可能返回 null,但是它可以抛出 NullPointerException
  • 至于你的比较,不要使用“包含”,而是使用 equalsIgnoreCase
  • 而第二个条件在 getOrganizationalname() 之后错过了 toLowerCase()
  • @Stultuske OP 需要“搜索字符串的一部分”,因此需要contains

标签: java list spring-boot search arraylist


【解决方案1】:

关于代码

   if(d.getOrganizationName().toLowerCase() != null 
      && d.getOrganizationName().contains(search.toLowerCase())) {
          listClone.add(d);
   }

这里有两个问题:

  • 你的空检查是错误的。如果 d.getOrganizationName()null(这显然会发生),调用 toLowerCase 将抛出 NullPointerException
  • 您支票的另一部分使用contains,但您没有使用toLowerCase

你想要的是

   if(d.getOrganizationName() != null
      && d.getOrganizationName().toLowerCase().contains(search.toLowerCase())) {
        listClone.add(d);
   }

【讨论】:

    猜你喜欢
    • 2012-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-15
    • 2013-09-26
    • 2023-03-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多