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


i have array of objects. each object customer record, customer id (int), first name (string), last name(string), , balance (double).

my problem not supposed have duplicate customer records, if appear in file twice, have update balance. cannot figure out how search array find out if need update balance or make new record in array.

i feel should in get/setters, not sure.

edit: clarify on "if appear in file twice, have update balance." have file made in notepad supposed customer list, has of information. if same customer shows twice, following day buy more stuff, not supposed create new object them since have object , place in array. instead, supposed take amount spent, , add existing balance within existing object.

edit2: thought give bit of code have read in values array. based off of example did in class, didn't have update anything, store information array , print if needed.

public customerlist(){     data = new customerrecord[100]; //i'm allowed 100 unique customers     try {         scanner input = new scanner(new file("records.txt"));         for(int = 0; < 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 using arrays in case. set more suitable it, definition, not have duplicate entries.

what need implement equals() , hashcode() methods in customer class use id (or id , name fields) not balance.

if reason need use arrays have 2 options:

  • sort array , use binary search find if customer there, nice if array doesn't change you're doing lot of updates
  • simply linear scan of array, checking each entry see if given customer there, if update balance, otherwise add new entry

it like:

public void updateoradd(customer cst) {   boolean exists = false;   for(customer existing : array) {     // !!! need implement own equals method in     // customer doesn't take account balance !!!     if(existing.equals(cst)) {       exists = true;       existing.updatebalance(cst.getbalance());       break;     }   }   if(!exists) {     // add cst array   } } 

the difference in runtime, set solution constant o(1) on average (unless incorrectly implement hashcode() method).


Comments

Popular posts from this blog

Payment information shows nothing in one page checkout page magento -

tcpdump - How to check if server received packet (acknowledged) -