我找不到以下任何信息:对java集合中的每个删除操作和添加操作
通常我有一个扩展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!");
}
}
的问题是remove方法不叫,如果我使用迭代器删除对象。每次在Java中添加或从Java集合中删除对象时,是否都有执行操作的方法?如果不是,我确实需要覆盖哪些方法或类才能确保我的集合保持一致,而不管以哪种方式删除或添加内容?
在你的情况下使用组合而不是继承可能会更容易。 – assylias 2014-10-29 18:36:30