假设我想在ArrayBag中添加3个形容词,并且通过使用JavaDoc for 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()
,如何在使用后删除该随机字符串?非常感谢任何帮助。
答案 0 :(得分:0)
答案在于在从grab()方法中删除ArrayBag中的元素之后更改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
}