Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Updating specific attribute of an ArrayList item

Tags:

java

arraylist

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);

        }
    }
}
like image 956
Sharkmen Avatar asked Jan 29 '19 08:01

Sharkmen


2 Answers

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

like image 118
Ruslan Avatar answered Oct 03 '22 15:10

Ruslan


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.

like image 25
Maroun Avatar answered Oct 03 '22 14:10

Maroun