Updating specific attribute of an ArrayList item

  • A+
Category:Languages

Item has name, price, condition attributes. I want to keep the priceand conditionbut replace the name.

For now I figured out this by creating new object but I think this is not best option. I just want to change one field of ArrayList item

public void modify(String name) {     for (Item i : item) {         if (i.getName().equalsIgnoreCase(name)) {             int position = item.indexOf(i);             System.out.println("New name: ");             String newName = in.nextLine();             Item updated = new Item(newName, i.getPrice(), i.getCondition(), i.getSize());             item.set(position, updated);          }     } } 

 


You don't have to insert a new item to ArrayList

public void modify(String name) {     for (Item i : item) {         if (i.getName().equalsIgnoreCase(name)) {             System.out.println("New name: ");             String newName = in.nextLine();             i.setName(newName);         }     } } 

It's supposed you have set methods for each field. Then you can update name, price, size this way

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: