假设我要向ArrayBag中添加3个形容词,并且通过使用JavaDoc中的ArrayBag中的每种方法,如果grab()方法从ArrayBag中随机获取一个形容词,那么我应该怎么做在使用后一次删除一个形容词并使用它?
/**
* Accessor method to retrieve a random element from this ArrayBag and will
* remove the grabbed element from the ArrayBag
*
* @return A randomly selected element from this ArrayBag
* @throws java.lang.IllegalStateException Indicated that the ArrayBag is
* empty
*/
public E grab() {
int i;
//E n;
if (items == 0) {
throw new IllegalStateException("ArrayBag size is empty");
}
i = (int) (Math.random() * items + 1);
// n = elementArray[i - 1];
//if (items != 0) {
// remove(n);
//}
return elementArray[i - 1];
}
和
/**
* Remove one specified element from this ArrayBag
*
* @param target The element to remove from this ArrayBag
* @return True if the element was removed from this ArrayBag; false
* otherwise
*/
public boolean remove(E target) {
int i;
if (target == null) {
i = 0;
while ((i < items) && (elementArray[i] != null)) {
i++;
}
} else {
i = 0;
while ((i < items) && (!target.equals(elementArray[i]))) {
i++;
}
}
if (i == items) {
return false;
} else {
items--;
elementArray[i] = elementArray[items];
elementArray[items] = null;
return true;
}
}
我尝试过的当前代码。
printText(3, "adjectives");
adjectives.ensureCapacity(3);
adjective = input.nextLine();
String[] arr = adjective.split(" ");
for(String ss : arr) {
adjectives.add(ss);
呼叫
adjectives.grab()
后,如何在使用随机字符串后将其删除?任何帮助深表感谢。 最佳答案
答案就在于从ArrayBag中删除所有在handle()方法内的元素之后,更改ArrayBag的大小。
/**
* Accessor method to retrieve a random element from this ArrayBag and will
* remove the grabbed element from the ArrayBag
*
* @return A randomly selected element from this ArrayBag
* @throws java.lang.IllegalStateException Indicated that the ArrayBag is
* empty
*/
public E grab() {
int i;
E n;
if (items == 0) {
throw new IllegalStateException("ArrayBag size is empty");
}
i = (int) (Math.random() * items + 1);
n = elementArray[i - 1];
remove(n);
trimToSize();
return n
}