简体   繁体   中英

How to search an array of objects and then update a part of the object in java?

I have an Array of objects. Each object is a customer record, which is the customer ID (int), first name (String), last name(String), and balance (double).

My problem is that i am not supposed to have duplicate customer records, so if they appear in the file twice, I have to just update their balance. I cannot figure out how to search the array to find out if i need to just update the balance or make a new record in the array.

I feel like i should do this in the get/setters, but i am not exactly sure.

edit: to clarify on " if they appear in the file twice, I have to just update their balance. " I have a file i made in notepad which is supposed to be a customer list, which has all of their information. if the same customer shows up twice, say the following day to buy more stuff, i am not supposed to create a new object for them since they already have an object and a place in the array. instead, i am supposed to take the amount they spent, and add it to their already existing balance within their existing object.

edit2: i thought i would give you the bit of code i have already where i read in the values into the array. i based this off of the example we did in class, but we didn't have to update anything, just store information into an array and print it if needed.

public CustomerList(){
    data = new CustomerRecord[100]; //i'm only allowed 100 unique customers
    try {
        Scanner input = new Scanner(new File("Records.txt"));
        for(int i = 0; i < 100; ++i){
            data[i] = new CustomerRecord();
            data[i].setcustomerNumber(input.nextInt());
            data[i].setfirstName(input.next());
            data[i].setlastName(input.next());
            data[i].setTransactionAmount(input.nextDouble());
        }

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }

}   

You shouldn't be using arrays in that case. A Set would be much more suitable as it, by definition, does not have duplicate entries.

What you need to do is to implement the equals() and hashCode() methods in your Customer class so they only use id (or id and name fields) but not balance .

If for some reason you need to use arrays you have two options:

  • sort the array and use binary search to find if the customer is there, this is nice if the array doesn't change much but you're doing a lot of updates
  • simply do a linear scan of the array, checking each entry to see if a given customer is already there, if so then update the balance, otherwise add it as a new entry

It would be something like:

public void updateOrAdd(Customer cst) {
  boolean exists = false;
  for(Customer existing : array) {
    // !!! You need to implement your own equals method in the
    // customer so it doesn't take into account the balance !!!
    if(existing.equals(cst)) {
      exists = true;
      existing.updateBalance(cst.getBalance());
      break;
    }
  }
  if(!exists) {
    // add the cst to the array
  }
}

The difference is in runtime, the set solution will be constant O(1) on average (unless you incorrectly implement your hashCode() method).

Suppose you have a Customer array:

Customer[] customers = new Customer[size];
... // fill the array with data

Then you get a new customer object called newCustomer . You need to search for newCustomer in your array and, update it if it is already there, or add it if it's not. So you can do something like this:

// Return, if it exists, a customer with id equal to newCustomer.getId()
Optional<Customer> existingCustomer =
    Arrays.stream(customers)
          .filter(c -> newCustomer.getId().equals(c.getId()))
          .findFirst();
if (existingCustomer.isPresent()) {
    // update the customer object with newCustomer information as appropriate
    Customer customer = existingCustomer.get();
    // assuming you have an updateBalance() method
    customer.updateBalance(newCustomer.amountSpent());
} else {
    // if the customer is not in the array already, add them to the current position
    customers[currentIndex] = newCustomer;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM