java一个简单的程序问题

来源:百度知道 编辑:UC知道 时间:2024/06/14 20:53:30
import java.util.*;class Counts {int i = 0;int m = 0;
public Counts(int i) {this.i = i;}public String toString() {
return Integer.toString(i);}public boolean equals(Object o) {
if (o instanceof Counts && ((Counts) o).i == this.i) {
return true;} else {return false;}}
public int hashCode() {return new Integer(i).hashCode();}}
public class E29_HashSetStatistics {
public static void main(String[] args) {Random r = new Random();
Set s = new HashSet();for (int k = 0; k < 1000; k++) {
int rand = r.nextInt(20);if (s.contains(new Counts(rand))) {
new Counts(rand).m++;} else {s.add(new Counts(rand));}}
Iterator it = s.iterator();while (it.hasNext()) {
Counts c = (Counts) it.next();System.out.println(c + ":" + (c.m));}}}我这段代码是想利用Set不添加重复元素的特性来捕获随即数的分布可是结果变成这样了15:0 4:0 19:0 8:0 11:0 16:0 18:0 3:0 7:0 12:0 17:0 2:0 13:0 9:0 6:0 1:0 14:0 10:0 5:0 0:0 谁给我看看谢谢了!

if (s.contains(new Counts(rand)))
{
new Counts(rand).m++; //这个地方计数的对象,和set中放的对象不是同一个对象,这里创建了一个新的对象,应该是从Set中取得那个对应的对象

}

可以将Set改成Map来实现。

该了一下,可以达到你要的效果
public class E29_HashSetStatistics {
public static void main(String[] args)
{
Random r = new Random();
Map<Integer,Counts> m = new HashMap<Integer,Counts>();
for (int k = 0; k < 1000; k++)
{
int rand = r.nextInt(20);

if ( m.containsKey(rand) )
{
m.get(rand).m++;

}
else {m.put( rand,new Counts(rand) );}
}

for (Integer i : m.keySet())
{
Counts c = m.get(i);
System.out.println(c + ":" + (c.m));
}
}
}

大概看了一下,
你这样试试看
首先补齐m的getter/setter方法
判断如果已经包含后应该先remove掉,再add进去进行
Counts count = new Counts(rand);
if (s.contains(count)){
count.setM(count.getM()