You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现SimpleHistogram类的setCount方法,设置元素指定出现次数?

完善后的SimpleHistogram泛型类实现

以下是修正后的完整代码,解决了元素匹配、数组扩容、边界校验等核心问题:

public class SimpleHistogram<DT> {
    private DT[] items;
    private int[] counts;
    private int size;
    private static final int DEFAULT_CAPACITY = 10;

    @SuppressWarnings("unchecked")
    public SimpleHistogram() {
        items = (DT[]) new Object[DEFAULT_CAPACITY];
        counts = new int[DEFAULT_CAPACITY];
        size = 0;
    }

    @SuppressWarnings("unchecked")
    public SimpleHistogram(DT[] initialItems) {
        if (initialItems == null) {
            throw new IllegalArgumentException("Initial items array cannot be null");
        }
        items = (DT[]) new Object[Math.max(DEFAULT_CAPACITY, initialItems.length)];
        counts = new int[items.length];
        size = 0;
        // 初始化时将传入数组元素加入直方图,初始次数设为1
        for (DT item : initialItems) {
            setCount(item, 1);
        }
    }

    public void setCount(DT item, int count) {
        // 校验count合法性
        if (count < 0) {
            throw new IllegalArgumentException("Count cannot be negative");
        }

        // 查找目标元素索引
        int index = findItemIndex(item);
        if (index != -1) {
            // 找到则更新次数
            counts[index] = count;
            return;
        }

        // 未找到则扩容数组(如果需要)
        if (size == items.length) {
            resize(items.length * 2);
        }

        // 添加新元素及对应次数
        items[size] = item;
        counts[size] = count;
        size++;
    }

    // 辅助方法:查找元素在数组中的索引,未找到返回-1
    private int findItemIndex(DT item) {
        for (int i = 0; i < size; i++) {
            DT current = items[i];
            // 单独处理null元素,避免空指针异常
            if (item == null) {
                if (current == null) return i;
            } else {
                if (item.equals(current)) return i;
            }
        }
        return -1;
    }

    // 辅助方法:扩容数组
    @SuppressWarnings("unchecked")
    private void resize(int newCapacity) {
        DT[] newItems = (DT[]) new Object[newCapacity];
        int[] newCounts = new int[newCapacity];
        // 复制原有数据
        System.arraycopy(items, 0, newItems, 0, size);
        System.arraycopy(counts, 0, newCounts, 0, size);
        items = newItems;
        counts = newCounts;
    }

    // 辅助方法:获取元素的当前次数,方便测试
    public int getCount(DT item) {
        int index = findItemIndex(item);
        return index != -1 ? counts[index] : 0;
    }

    // 辅助方法:打印直方图内容,方便调试
    public void printHistogram() {
        for (int i = 0; i < size; i++) {
            System.out.printf("Item: %s, Count: %d%n", items[i], counts[i]);
        }
    }
}

核心修正说明

  • 泛型数组初始化:通过(DT[]) new Object[capacity]实现泛型数组创建,添加注解抑制类型转换警告,这是Java泛型数组初始化的标准方案。
  • null元素兼容:在元素查找逻辑中单独处理null,避免调用equals时抛出空指针异常,同时保证null元素能被正确识别和更新。
  • 自动扩容:当数组容量不足时自动翻倍扩容,解决了原代码可能出现的数组越界问题。
  • 参数校验:添加count非负校验,避免非法的次数设置。
  • 初始化逻辑统一:带初始数组的构造函数通过调用setCount初始化元素,保证逻辑一致性。

测试用例验证

public class SimpleHistogramTest {
    public static void main(String[] args) {
        // 测试1:基础更新与添加
        SimpleHistogram<String> strHist = new SimpleHistogram<>();
        strHist.setCount("Apple", 5);
        strHist.setCount("Banana", 3);
        strHist.setCount("Apple", 7); // 更新已有元素次数
        System.out.println("Test 1 Results:");
        strHist.printHistogram();

        // 测试2:null元素处理
        SimpleHistogram<String> nullHist = new SimpleHistogram<>();
        nullHist.setCount(null, 2);
        nullHist.setCount("Orange", 4);
        nullHist.setCount(null, 5); // 更新null元素次数
        System.out.println("\nTest 2 Results:");
        nullHist.printHistogram();

        // 测试3:初始数组初始化
        Integer[] nums = {1, 2, 3, 2, 1};
        SimpleHistogram<Integer> numHist = new SimpleHistogram<>(nums);
        numHist.setCount(3, 10); // 更新已有元素次数
        numHist.setCount(4, 6); // 添加新元素
        System.out.println("\nTest 3 Results:");
        numHist.printHistogram();

        // 测试4:非法count校验
        try {
            strHist.setCount("Grape", -2);
        } catch (IllegalArgumentException e) {
            System.out.println("\nTest 4 Results: " + e.getMessage());
        }
    }
}

内容的提问来源于stack exchange,提问作者user18984687

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 14:01:04