我有一个实现Bag的类,该Bag可以容纳无限数量的字符串,并且支持接口中的方法。我必须实现以下类:

Simplebag(此类按添加顺序包含字符串)
BagWithoutRepetitions(此类与Simplebag相同,但没有重复项)

我的问题是我不知道类的设置如何工作,以及如何引用包含方法的类。

到目前为止,我已经掌握了这一点,但是无法使用它进行任何测试,因为我确定自己错误地引用了这些类:

public interface Bag {

    public static void main(String[] args) {
    }

    class SimpleBag implements Bag {
        ArrayList<String> bag = new ArrayList<String>();
    }


这是界面

import java.util.ArrayList;


public interface Bag {


/** Add the string "str" to the strings in the bag as the last
 * element. It str was added then the method returns "true" and
 * "false" otherwise.
 * @param str
 * @return true iff succesfully added
 */
public  boolean addString(String str);

/** Removes all ocurrences of "str" from the bag.
 * If "str" occurred at least once in the bag then the method
 * returns "true" and "false" otherwise.
 * @param str
 * @return true iff str occured at least once
 */
public boolean removeAllOccurrences(String str);

/** Returns the string which currently is at the position given
 * by "index". In case the operation cannot be conducted, the
 * method returns "null".
 * @param index
 * @return string at index or null
 */
public  String getString(int index);

/** returns the number of elements currently in the bag.
 *  Indexing starts with 0.
 *
 * @return number of elements in the bag
 */
public  int noOfElements();
}


我怎么从这里继续?

最佳答案

SimpleBag需要是一个单独的类。

public class SimpleBag implements Bag {
}


SimpleBag需要包含出现在Bag中的所有方法。
这是一个不完整的骨架。

public class SimpleBag implements Bag {
    public boolean addString(String str) {
        // TODO: Complete.
        return false; // To make sure this code compiles.
    }

    public boolean removeAllOccurrences(String str) {
        // TODO: Complete.
        return false; // To make sure this code compiles.
    }

    public String getString(int index) {
        // TODO: Complete.
        return null; // To make sure this code compiles.
    }

    public int noOfElements() {
        // TODO: Complete.
        return 0; // To make sure this code compiles.
    }
}


同样,创建另一个类BagWithoutRepetitions,该类也包含接口Bag中的所有方法。这是一个更加最小的骨架。

public class BagWithoutRepetitions implements Bag {
}


然后,您可以编写另一个类来测试您的SimpleBag(和BagWithoutRepetitions)类。
这是该测试器类的框架。

public class BagTester {
    public static void main(String[] args) {
        Bag bag = new SimpleBag();
        bag.addString("George");
        bag.addString("Best");
        bag.addString("Northern");
        bag.addString("Ireland");
        bag.addString("Manchester");
        bag.addString("United");
        int count = bag.noOfElements();
        System.out.printf("Bag contains %d elements.%n", count);
    }
}


尝试完成以上框架。编辑您的问题并添加您将编写的代码,并指出您遇到的困难。

祝好运!

10-06 06:53