gpt4 book ai didi

Java如何创建自定义异常来限制HashMap的大小

转载 作者:行者123 更新时间:2023-12-01 17:09:25 31 4
gpt4 key购买 nike

我有一个将新项目插入到HashMap的方法,我想通过抛出异常来限制HashMap的大小HashMap 的大小大于特定值,例如 100,下面是我的实现:

public void addToHashMap(String id, Object value) throws HashMapOutOfBoundException{
hashMap.put(id,value);
}

private class HashMapOutOfBoundException extends Exception{
//what should I do inside this class?
}

最佳答案

为什么不简单一点:

public void addToHashMap(String id, Object value) {
if (hashMap.size()+1 > MAX_SIZE)
throw new HashMapOutOfBoundException();
hashMap.put(id,value);
}

public class HashMapOutOfBoundException extends RuntimeException {}

来自javadoc:

RuntimeException and its subclasses are unchecked exceptions. Unchecked exceptions do not need to be declared in a method or constructor's throws clause if they can be thrown by the execution of the method or constructor and propagate outside the method or constructor boundary.

关于Java如何创建自定义异常来限制HashMap的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24326693/

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