Independent capacity rules

A storage allocator uses function objects to accept or reject requests for whole storage blocks. Each object retains its own remaining capacity. The method returns 1 for an accepted request and 0 for a rejected request.


Java
class CapacityRule {
    private int remaining;

    CapacityRule(int blocks) {
        remaining = blocks;
    }

    public int apply(int requested) {
        if (requested <= remaining) {
            remaining -= requested;
            return 1;
        }
        return 0;
    }

    public int remaining() {
        return remaining;
    }
}


Two separate objects are constructed:


Java
CapacityRule gateA = new CapacityRule(8);
CapacityRule gateB = new CapacityRule(5);


Execute the calls in table order. Enter each returned integer and the remaining capacity of the object called immediately afterward. All entries are exact integers; capacities are in blocks.

CallReturned integerCalled object's remaining blocks
gateA.apply(3)
gateB.apply(4)
gateA.apply(6)
gateB.apply(1)

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

More Function Objects Questions: