gpt4 book ai didi

Java在HashSet中找到最常见的值

转载 作者:行者123 更新时间:2023-12-01 06:41:12 24 4
gpt4 key购买 nike

好吧,这是一个基本问题,但我想知道解决这个问题的最佳方法是什么......

我有一个要向其添加对象的 HashSet,.add() 方法只会添加一个对象(如果该对象尚不存在)。但我想做的是添加所有对象,然后最后得到以下结果..

-唯一(不同)对象的数量
- 对象的平均频率

有人能给我指出正确的方向吗?

提前致谢

最佳答案

使用 HashMap 。使用条目作为键,并将它们映射到整数以保持计数。

编辑:您可能想要包装 HashMap,以确保每次添加或删除对象时,计数器都会得到适当的修改。
让您开始:

class MapWrapper<Key>
{
private Map<Key,Integer> map = new HashMap<Key, Integer>();

void add( Key key )
{
Integer n = map.get( key );
if ( n == null )
{
map.put( key, 1 );
}
else
{
map.put( key, new Integer( n + 1 ));
}
}

int occurrences( Key k )
{
Integer n = map.get( k );
if ( n == null )
{
return 0;
}
else
{
return n;
}
}
}

关于Java在HashSet中找到最常见的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7646831/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com