java - 将字符串与 ArrayList 中对象的字符串进行比较时,字符串比较不起作用
问题描述
我正在尝试将存储在 ArrayList 中的对象的字符串字段与输入字符串进行比较。
在这种情况下,我有一个数组列表——ArrayList<Customer>
并且我创建了几个基于客户的对象,这些对象只有name
andemail
字段。我正在尝试通过检查名称和电子邮件字段的输入来检查重复项,如下所示:
import java.util.ArrayList;
class Customer
{
private String cName;
private String cEmail;
public Customer(String custName, String custEmail)
{
this.cName = custName;
this.cEmail = custEmail;
}
public String getName()
{
return cName;
}
public String getEmail()
{
return cEmail;
}
}
class Main {
public static void main(String args[])
{
ArrayList<Customer> custArr = new ArrayList();
Customer aaa = new Customer ("John Perkins", "john.perkins@mail.com");
Customer bbb = new Customer ("Peh Yan", "peh.yan@mail.com");
Customer ccc = new Customer ("In Koh", "inkoh@mail.com");
custArr.add(aaa);
custArr.add(bbb);
custArr.add(ccc);
System.out.println("Added in test customers info.");
// Assume these are the inputted values
String name = "in koh";
String email = "inKoh@mail.com";
for(int i=0; i<custArr.size(); i++)
{
// if (custArr.get(i).getName().toLowerCase() == email.toLowerCase() &&
// custArr.get(i).getEmail().toLowerCase() == email.toLowerCase())
if (custArr.get(i).getEmail().toLowerCase() == email.toLowerCase())
{
System.out.println("Error! User already exists in the system");
}
}
}
}
但是,除非我的输入字符串字段的措辞与测试数据完全相同,否则字符串比较似乎不起作用。例如,String name = "in koh"
不起作用,但如果我将其写为String name = "In Koh"
,它将起作用。
需要对此有一些见解,因为我很确定两者getName
并且getEmail
确实返回了 String 值
解决方案
对于字符串比较使用equals()。
代替
if (custArr.get(i).getEmail().toLowerCase() == email.toLowerCase())
和
if (custArr.get(i).getEmail().toLowerCase().equals(email.toLowerCase()))
推荐阅读
- excel - 如何使用 COUNTIF 计算日期范围之间的特定文本?
- kdb - kdb:避免在字符串中转义双引号
- python - 层的输入与预期输入的层不兼容
- python - 在不显示元素的情况下测试 Python Tkinter GUI 应用程序
- ruby-on-rails - 为什么我的 js 的子文件夹(在 sublime 上)带有淡淡的灰色?
- javascript - 如何让我的第一个可折叠默认打开
- c# - 如何使用 .NET 4 的 Lazy 解决依赖关系
输入 ASP.Net Core - node.js - 在 react js 中如何将带有参数的 axios GET 方法请求发送到 Node js 以及在 Node js 中如何获取这些参数
- html - bootstrap 3 -> 5 导航栏可折叠
- python - python tkinter快速绘制信封