Sharkmen
Sharkmen

Reputation: 63

Updating specific attribute of an ArrayList item

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

        }
    }
}

Upvotes: 5

Views: 2534

Answers (3)

aBnormaLz
aBnormaLz

Reputation: 847

Actually after finding the item you don't need to iterate though the whole list for no purpose, so it's better to extract your find method as a static function into Item class like

public void modify(String name) {
    System.out.println("New name: ");
    String newName = in.nextLine();
    Item itemToModify = Item.findByName(item, name);
    if(itemToModify != null) {
        itemToModify.setName(newName);
    } else {
        System.out.println("Item not found with that name!");
    }
}

Item.java

public static Item findByName(Collection<Item> items, String name) {
    for(Item item : items) {
        if(item.getName().equalsIgnoreCase(name)) {
            return item;
        }
    }
    return null;
}

Imagine if you have like a million items in your collection, and you want to update the secong. You iterate through te remaining 999.998 for nothing.

Upvotes: 0

Ruslan
Ruslan

Reputation: 6300

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

Upvotes: 7

Maroun
Maroun

Reputation: 95978

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.

Upvotes: 6

Related Questions