首页 > 解决方案 > 将字符串与 ArrayList 中对象的字符串进行比较时,字符串比较不起作用

问题描述

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

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

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 值

标签: javastringarraylist

解决方案


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

代替

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

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

推荐阅读