有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java数据结构,用于计算相等项的频率

我需要像HashSet这样的数据结构

  1. 不应将同一项添加到集合中
  2. 但与其添加同一项,不如计算添加该项的次数

据我所知HashSet首先计算hashCode,如果hashCode相同,它会检查equals方法,如果为true,则它不会添加一个项,否则具有相同hashCode但另一个equals的项将添加到bucket链表中

我需要做的是只保留像Set那样的唯一对象,但只使用equals方法,如果对象等于与每个对象关联的递增计数器

是否已经实现了这样的数据结构,或者我应该创建自己的数据结构


共 (2) 个答案

  1. # 1 楼答案

    最简单的方法(没有依赖项)是使用HashMap<Element, Integer>。或者您可以使用Guava的^{},它有一个count(Object)方法来获取集合中某个对象的出现次数

  2. # 2 楼答案

    看来你真正需要的是一张地图。对于每一件物品,你都可以得到物品的数量

    public class ItemCounter<T>{
    
        private Map<T, Integer> counts = new HashMap<T, Integer>();
    
        public void addItem(T item){
            Integer numberOfOcurrences = counts.get( item );            
            numberOfOcurrences = numberOfOcurrences == null ? 0 : numberOfOcurrences+1;
            counts.put( item,  numberOfOcurrences);            
        }
    
        public Integer getCount( T item ){
            Integer numberOfOcurrences = counts.get( item );    
            return numberOfOcurrences == null ? 0 : numberOfOcurrences;
        }
    }