从java中的对象数组中删除对象

时间:2016-07-12 08:57:15

标签: java

import java.util.StringTokenizer;

class Count {
    int count;
    String name;

    void SetCount(int c, String n) {
        this.count = c;
        this.name = n;
    }

    void Show() {
        System.out.print("Word= " + name);
        System.out.print(" Count= " + count);
        System.out.println();
    }
}

class Contains2 extends Count {
    public static void main(String args[]) {
        String s = "Hello this program will repeat itself for this useless purpose and will not end until it repeats itself again and again and again so watch out";
        int i, c2, j;

        StringTokenizer st = new StringTokenizer(s, " ");
        c2 = st.countTokens();

        String[] test = new String[c2];
        Count[] c = new Count[c2];

        for (i = 0; i < c2; i++) {
            c[i] = new Count();
        }

        i = 0;

        while (st.hasMoreTokens()) {
            String token = st.nextToken();

            test[i] = token;
            c[i].SetCount(0, test[i]);
            i++;
        }

        for (i = 0; i < c2; i++) {
            for (j = 0; j < c2; j++) {
                if (c[i].name.equals(test[j]))
                    c[i].count += 1;
            }
        }

        for (i = 0; i < c2; i++) {
            c[i].Show();
        }
    }
}

所以我做了这个小程序来计算段落中每个单词重复的数字。它按计划工作,但现在我得到每个单词的重复,因为我为每个单词创建了单独的对象并将它们全部打印出来。所以有什么方法可以删除重复的单词,我的意思是根据他们的名字删除这些对象。我可以将它们设置为null但它仍会打印它们所以我只想摆脱它们或以某种方式跳过它们

1 个答案:

答案 0 :(得分:0)

创建数组后,无法调整数组的大小。您只能创建一个具有不同大小的新数组并复制非null元素。

你也可以将元素设置为null,然后忽略那些要打印的元素......

for (i = 0; i < c2; i++) {
    if (c[i] != null)
        c[i].Show();
}

另一种方法是使用List,它允许您删除元素。

或者,可以使用从单词到计数的Map<String, Integer>映射。在这种情况下,您甚至不需要Count类:

String s = "Hello this program will repeat itself for this useless purpose and will not end until it repeats itself again and again and again so watch out";
StringTokenizer st = new StringTokenizer(s, " ");

Map<String, Integer> map = new HashMap<>();

while (st.hasMoreTokens()) {
    map.merge(st.nextToken(), 1, Integer::sum);
}

for (Map.Entry<String, Integer> e : map.entrySet()) {
    System.out.print("Word= " + e.getKey());
    System.out.print(" Count= " + e.getValue());
    System.out.println();
}