I’m trying to select and get values from customer objects. What I want to do is to enter a personal number like “702312” and search after the customer objects that has a data member personal number that are equal to “702312”. And when I found it I want to get the rest of the values or change it’s content. This is some code that creates the customer objects from the class Customer and then it’s stored in a arraylist.
// create a new customer object and send personal number, name and account number to constructor
Customer customer = new Customer(personalNumber, name, newAccountNumber);
// create an arraylist to store customer objects
ArrayList<Customer> customerList = new ArrayList<Customer>();
// add the new customer object to arraylist that holds all customer objects
customerList.add(customer);
I have tried to reach the values like this, but it’s not working, so I’m looking for some help?
// search for customer
for (Customer customer : customerList) {
if(customer.getAccountOwnerPersonalNumber() == "702312"){
System.out.println("OK!!!");
}
}
And instead of:
if(customer.getAccountOwnerPersonalNumber() == "702312")...
I have tried this:
if(customer.personalNumber == "702312")...
Finally I have also tested it like this:
for(int i=0;i<customerList.size();i++){
if(customerList.get(i).getAccountOwnerName() == "702312");
System.out.println("OK");
break;
}
I’m not sure if I’m doing right!? Help is preciated! Thanks!
You need to use the
equals()method to compare objects likeStrings by their internal value (otherwise they will only be compared by reference):or, better, if it can potentially return
null:or, if applicable, just make it a primitive like
int, so that==will work the way you intended:with