【问题标题】:String comparison is not working when comparing it against object's string in ArrayList [duplicate]将字符串与 ArrayList 中的对象字符串进行比较时,字符串比较不起作用 [重复]
【发布时间】:2021-09-02 07:57:22
【问题描述】:

我正在尝试将存储在 ArrayList 中的对象的字符串字段与输入字符串进行比较。

在这种情况下,我有一个数组列表 - ArrayList<Customer>,并且我创建了几个基于客户的对象,这些对象只有 nameemail 字段。我正在尝试通过检查名称和电子邮件字段的输入来检查重复项,如下所示:

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"就行了。

需要对此有所了解,因为我很确定 getNamegetEmail 确实都在返回字符串值

【问题讨论】:

  • Java 中的字符串比较通常不是通过== 完成的。

标签: java string arraylist


【解决方案1】:

对于字符串比较使用 equals()

替换

if (custArr.get(i).getEmail().toLowerCase() == email.toLowerCase())

if (custArr.get(i).getEmail().toLowerCase().equals(email.toLowerCase()))

【讨论】:

    猜你喜欢
    • 2023-03-23
    • 1970-01-01
    • 1970-01-01
    • 2021-07-10
    • 2014-10-07
    • 2014-11-08
    • 2015-01-30
    • 1970-01-01
    • 2017-02-20
    相关资源
    最近更新 更多