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
You can have an updateName method in the Item class, and then only update the object's name:
item.get(index).updateName(newName);
item.get(index) returns an Item object, on which you apply the updateName method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With