使用add,remove和contains方法实现数据结构

时间:2013-12-04 19:08:30

标签: java hashset

我想在java中创建一个数据结构,基本上我已经研究了这个,最好的结构是一个允许重复的列表,我想在没有Java API的情况下尝试这个。我不知道该怎么做甚至开始这个,已经做了大约6个小时的研究。

class WordStoringTest implements WordStore {
    private String[] words;

    public WordStoringTest(int n){
        words = new String[n];
    }
    public void add(String word) {
        int count = words.length+1;
        words = new String[count];
    }

    @Override
    public int count(String word) {
    int count =0;
        for(int i=0; i<words.length; i++){
            if(words[i].equals(word)){
                count++;
            }
        }
        return count;
    }

    @Override
    public void remove(String word) {
        // TODO Auto-generated method stub
    }
}

我不知道从哪里开始请给我一些指导:)谢谢

2 个答案:

答案 0 :(得分:0)

你的代码中存在一些不一致的东西,这使得理解起来非常困难....例如,你建议'set'是你想要它的东西,但是你有一个count(...)方法表明你期望'set'中的值有多个副本。传统的理解是“集合”的成员与集合中的任何其他成员不是equals()

此外,您现在拥有的只是一组数据。这个数据阵列没有给你带来任何好处....最有利的事情是(你在java.util。*中得到的各种东西):

  • 所有值都是唯一的
  • 搜索数据的能力是“快速”
  • 减少了维护,因为数据会根据您的需要增长/缩小。
  • 数据始终排序

... 某些东西必须比普通数组更好。

现在,即使你添加()方法仍然有效:

public void add(String word) {
    int count = words.length+1;
    words = new String[count];
}

上述方法将删除数组中的所有数据,方法是创建一个空数据,这就是全部数据。

我建议您浏览一些标准示例,了解事情是如何完成的...考虑一下.... google basic java data structures ....我发现this blog which looks useful

答案 1 :(得分:0)

这个怎么样(经过测试)。

注意:这就像一个Java List,Not Set因为有重复。

这不是最佳实施方案。我们可以为像initialCapacity这样的字数组准备数组缓冲区。

公共类WordStoringTest实现WordStore {

private String[] words;

public WordStoringTest() {
    this(0);
}

public WordStoringTest(int n) {
    this.words = new String[n];
}

public void add(String word) {
    String[] newWords = new String[this.words.length + 1];
    System.arraycopy(this.words, 0, newWords, 0, this.words.length);
    newWords[newWords.length - 1] = word;
    this.words = newWords;
}

// @Override
public int count(String word) {
    int count = 0;
    for (String w : this.words) {
        if (word.equals(w)) {
            count++;
        }
    }
    return count;
}

// @Override
public void remove(String word) {
    int pos = 0;
    String[] temp = this.words;
    while (pos < temp.length) {
        String w = temp[pos];
        if (w.equals(word)) {
            String[] newTemp = new String[temp.length - 1];
            if (pos == 0) {
                System.arraycopy(temp, 1, newTemp, 0, newTemp.length);
            } else if (pos == temp.length - 1) {
                System.arraycopy(temp, 0, newTemp, 0, newTemp.length);
            } else {
                System.arraycopy(temp, 0, newTemp, 0, pos);
                System.arraycopy(temp, pos + 1, newTemp, pos, newTemp.length - pos);
            }
            temp = newTemp;
        } else {
            pos++;
        }
    }
    this.words = temp;
}

}

相关问题