我找不到以下任何信息:對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