我在第12_01部分.藏身处.我关心的方法:公共T takeFromHideout(),我知道如何做到这一点,但我想知道是否有一个更好的方法. 我的 idea 是通过创建新的对象来"复制"对象,删除第一个对象并返回它的副本. 有没有一种方法可以返回并删除对象,而不会产生这种"垃圾"副本?
练习:
实现一个名为HhideOut的类,该类具有单个泛型类型 参数.从类创建的对象只能隐藏一个对象 一次来一次.该类应提供无参数构造函数,如下所示 以及以下三种方法:
PUBLIC VALID putIntoHideout(T ToHide)将类型为 根据指定给类的类型参数,将 藏身之处.如果某个对象已经在隐藏中,它将 消失吧.
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.个
公共布尔值isInHideout()如果存在 藏身之处的物体.以防藏身之处没有任何物体, 它应该返回值FALSE.
带复制对象的代码.
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;
}
}