【发布时间】:2021-09-02 07:57:22
【问题描述】:
我正在尝试将存储在 ArrayList 中的对象的字符串字段与输入字符串进行比较。
在这种情况下,我有一个数组列表 - ArrayList<Customer>,并且我创建了几个基于客户的对象,这些对象只有 name 和 email 字段。我正在尝试通过检查名称和电子邮件字段的输入来检查重复项,如下所示:
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 确实都在返回字符串值
【问题讨论】:
-
Java 中的字符串比较通常不是通过
==完成的。