Java Mooc.fi Part 12_01.Hideout – return and delete method

I’m at Part 12_01.Hideout. Im concerned about method: public T takeFromHideout(), i know how to do it but i wonder if there is a better way.
My idea is to “copy” the object by making the new one, remove the first one and return the copy of it.
Is there a way to return and then delete object without making this “garbage” copy?

Exercise:

Implement a class called Hideout, which has a single generic type
parameter. The object created from the class may only hide one object
at a time. The class should provide a parameterless constructor as
well as the following three methods:

public void putIntoHideout(T toHide) puts an object with a type in
accordance with the type parameter given to the the class into the
hideout. In case an object is already in the hideout, it will
disappear.

public T takeFromHideout() takes out the object with a type in accordance with the type parameter given to the the class from the
hideout. In case there is nothing in the hideout, we return null.
Calling the method returns the object in the hideout and removes the
object from the hideout.

public boolean isInHideout() returns the value true if there is an
object in the hideout. In case there isn’t an object in the hideout,
it should return the value false.

My code with copied object.

public class Hideout<T> {

    private T object;

    public void putIntoHideout(T toHide) {
        this.object = toHide;
    }

    public T takeFromHideout() {
        T copy = this.object;
        this.object = null;
        return copy;
    }

    public boolean isInHideout() {
        return this.object != null;
    }
}

No, your implementation is correct. Since you need to return the object and remove it from the hideout, it makes sense that you copy it, remove it and return the copy consequently with your

    public T takeFromHideout() {
        T copy = this.object;
        this.object = null;
        return copy;
    }

Leave a Comment