java - ArrayBag的grab()和remove()方法,使用.grab()方法后如何删除String?

标签 java netbeans methods

假设我想向 ArrayBag 添加 3 个形容词,并且通过使用 ArrayBag 的 JavaDoc 中的每个方法,如果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(),我该如何删除使用过的随机字符串?非常感谢任何帮助。

最佳答案

答案在于在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
} 

关于java - ArrayBag的grab()和remove()方法,使用.grab()方法后如何删除String?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33560389/

相关文章:

java - Java 中的 try-catch 语法糖

java - 禁止互联网用户访问tomcat的index.jsp

java - 在 hibernate 中使用可序列化我使用什么底层数据库类型

C#:非静态字段、方法或属性需要对象引用

java - 触发 Gradle 测试时无法使用 commons-exec 在 Java 中运行命令行

netbeans - 如何恢复netbeans中关闭的输出窗口?

用于运行当前正在编辑的文件的 NetBeans 键盘快捷键

java - 使用 gwt 和 jsp 时 jetty 类路径出现问题

Magento:无法检索付款方式实例

python - 在 Python 中更改了对象