-1

I am trying to compare the string fields of an object that are stored in an ArrayList against input strings.

In this case, I have an arraylist - ArrayList<Customer> and I have created several Customer-based objects that only has the name and email fields. I am trying to check for duplicates by checking the inputs against the name and email fields as follows:

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");
            }
            
        }
    } 
}

However, the string comparison does not seems to be working unless my input string fields are worded exactly the same as the test data. For example, String name = "in koh" does not works, but if I wrote it as String name = "In Koh", it will works.

Need some insights on this as I am pretty sure both getName and getEmail are indeed returning String value

k_plan
  • 121
  • 1
  • 7

1 Answers1

1

for String comparison use equals().

Replace

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

with

if (custArr.get(i).getEmail().toLowerCase().equals(email.toLowerCase()))
Pirate
  • 2,886
  • 4
  • 24
  • 42