gpt4 book ai didi

java - 创建一个空的哈希集

转载 作者:太空宇宙 更新时间:2023-11-04 15:08:20 24 4
gpt4 key购买 nike

是否可以创建具有固定容量的 HashSet?具体来说,零之一和一之一。我还有其他方便的哈希集,这就是我不使用列表或其他东西的原因。

最佳答案

扩展哈希集:

import java.util.HashSet;

public class MyHashSet<Key> extends HashSet<Key> {

private int limit;

public MyHashSet(int limit) {
super();
this.limit = limit;
}

public boolean add(Key key) {
if (!contains(key) && size() == limit) {
throw new IndexOutOfBoundsException("Limit exceeded.");
} else {
return super.add(key);
}
}

public static void main(String[] args) {
HashSet<Integer> set = new MyHashSet<Integer>(1);
set.add(0);
set.add(1); // IndexOutOfBoundsException
}
}

关于java - 创建一个空的哈希集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21674457/

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