【发布时间】:2018-03-04 16:07:21
【问题描述】:
我不断收到越界异常。我检查了其他来源,这似乎主要是由于循环错误,但我的很好。
数组 _store 和 arr 都有条目。
标题代码:
public class ArrayMultiSet<E> implements Collection<E> {
/** Unless otherwise specified, the default length to which the backing store should be initialized. */
private static final int DEFAULT_INITIAL_CAPACITY = 16;
/** Array in which the elements in this multiset are stored. */
private E[] _store;
/**
* Array indices below this amount contain the active elements in this collection.
*/
private int _size;
/**
* Create a new empty multiset.
*/
public ArrayMultiSet() {
clear();
}
中间问题:
/**
* Resets the Multiset so that it only contains the entries in the given array. This overwrites the data previously in
* the Collection.
*
* @param arr The array whose entries will be the elements in the Collection
*/
@SuppressWarnings("unchecked")
public void fromArray(E[] arr) {
// IMPORTANT: You CANNOT set the backing store to be equal to ("alias")
// arr. If you did this, the calling method could make changes to the
// Multiset by updating the entries in arr rather than using the Multiset methods.
// This violates good OO practice and creates the potential for bugs and hacks.
_size = arr.length;
int i = 0;
while (i < _size) {
_store[i] = arr[i];
i++;
}
}
JUNIT:
【问题讨论】:
-
你为什么认为
_store足够大? -
我被告知要在 Junit 中分配他们的条目。
-
调试任何东西的方式相同。 ericlippert.com/2014/03/05/how-to-debug-small-programs 在这种情况下不需要调试太多
arr大于store -
是的,但是我在循环之前将它们分配给了彼此。
-
不,你没有。你不应该这样做。
标签: java arrays collections multiset