gpt4 book ai didi

java - 对 java 集合的每次删除和添加执行操作

转载 作者:太空宇宙 更新时间:2023-11-04 06:27:11 25 4
gpt4 key购买 nike

我找不到任何相关信息:

通常我有一个扩展 HashSet 的类。插入到该集合中的每个对象都有它的“所有者”,我想分别计算属于每个所有者的对象数量。所以我写了下面的代码:

public class Viruses extends HashSet<Virus> {
private HashMap<RaceName, Integer> countsPerRace = new HashMap<RaceName, Integer>();

@Override
public boolean add(Virus virus) {
if(super.add(virus)) {
RaceName race = virus.getOwner().getRace().getName();
if(countsPerRace.containsKey(race)) {
countsPerRace.put(race, countsPerRace.get(race) + 1);
} else {
countsPerRace.put(race, 1);
}
return true;
} else {
return false;
}
}

@Override
public boolean remove(Object virus) {
if(super.remove(virus)) {
RaceName race = ((Virus)virus).getOwner().getRace().getName();
if(countsPerRace.containsKey(race)) {
countsPerRace.put(race, countsPerRace.get(race) - 1);
} else {
throw new Exception("This should not happen...");
}
return true;
} else {
return false;
}
}

/**
* Returns number of viruses of given race.
* @param raceId raceName of the viruses, which is equivalent of an owner id as there should never be two owners with the same race
* @return number of viruses of given race.
*/
public int getCount(RaceName raceId) {
return countsPerRace.containsKey(raceId) ? countsPerRace.get(raceId) : 0;
}

// I don't need these, so I thought the best idea will be just to throw an exception here.
@Override
public boolean removeAll(Collection<?> collection) {
throw new EngineRuntimeException("Unsupported operation!");
}

@Override
public boolean addAll(Collection<? extends Virus> collection) {
throw new EngineRuntimeException("Unsupported operation!");
}
}

问题是,如果我使用迭代器删除对象,则不会调用删除方法。有没有一种方法可以在每次在 Java 集合中添加或删除对象时执行操作?如果不是,我必须重写哪些方法或类才能确保我的集合保持一致,无论我以哪种方式删除或添加内容?

最佳答案

正如您所发现的,不能保证迭代器使用公共(public) remove 方法。

在这种情况下,我强烈建议您考虑使用组合而不是继承。

但是,如果您想继续使用继承解决方案,则必须执行以下操作:

@Override
public Iterator<Virus> iterator() {
final Iterator<Virus> delegate = super.iterator();
return new Iterator<Virus>() {
@Override
public boolean hasNext() {
return delegate.hasNext();
}
@Override
public void remove() {
// put your custom remove logic here
// ...
delegate.remove();
}
@Override
public Virus next() {
return delegate.next();
}
};
}

关于java - 对 java 集合的每次删除和添加执行操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26638038/

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