通过声明数组bag是类ArrayBag的一个终态数据成员,可知变量bag中的引用不能改变。
虽然这是一种声明数组的的好做法,但数组元素bag[0], bag[1], ...的值还是可以改变的。但必须要阻止客户从bag中得到对数组的引用。否则会泄漏数组内容容易遭受恶意毁坏。
例如:
public String[] toArray()
{
return bag;
}
这个简单的定义肯定能将包元素所在的数组返回给客户,例如语句:
String[] bagArray = myBag.toArray();
能得到指向myBag中项的数组的引用。客户可以使用变量bagArray来显示myBag中的内容。
但是引用bagArray是数组bag自身,即bagArray是对象myBag中的私有实例变量bag的别名,所以客户可以直接访问该私有数据。
因此,应该方法toArray应该返回复制:
/** Retrieves all entries that are in this bag.
@return A newly allocated array of all the entries in the bag. */
public T[] toArray()
{
// The cast is safe because the new array contains null entries.
@SuppressWarnings("unchecked")
T[] result = (T[])new Object[numberOfEntries]; // unchecked cast
for (int index = 0; index < numberOfEntries; index++)
{
result[index] = bag[index];
}
return result;
}