Question: IN JAVA PLEASE: I need to write the code inside the method public boolean addItem(ShelfItem item). There are two variables . The variable numberOfShelfItems is

IN JAVA PLEASE: I need to write the code inside the method public boolean addItem(ShelfItem item). There are two variables. The variable numberOfShelfItems is initialized to 0 (numberOfShelfItems = 0). The variable ShelfItem[] shelves is initialized to 5, (shelves = new ShelfItem[5]).

This addItem method will add a new item after the current items already on the shelf. This means that the new item will always be added at index location numberOfShelfItems. If the array is full, the array will be expanded to make room for the new item. If the item was added, the method will return true and false otherwise. This is an O(1) method if there is free room to add a new item and an O(n) method if the array needs to expand.

1. Create a Boolean variable okToAddItem assigned as true

2. If there is not room for the new item

A. Expand the array capacity, assign what is returned to okToAddItem

4. If okToAddItem is true (there is room for the new item)

A. Add the new item at the index numberOfShelfItems

B. Increment numberOfShelfItems

7. Return true or false appropriately

Note: The expansion could potentially fail because there is no heap memory available. If the expansion returns false, do not attempt to add the new item. Start by assuming that it is okay to add the new item. If the expansion happens, update your assumption based on what the expansion method returns.

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!