2014-10-29 59 views
1

我找不到以下任何信息:对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集合中删除对象时,是否都有执行操作的方法?如果不是,我确实需要覆盖哪些方法或类才能确保我的集合保持一致,而不管以哪种方式删除或添加内容?

+1

在你的情况下使用组合而不是继承可能会更容易。 – assylias 2014-10-29 18:36:30

回答

1

正如您所发现的那样,不能保证迭代器使用公开的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(); 
     } 
    }; 
} 
+0

感谢您的建议。我决定使用构图并实现Collection。 – Arsen 2014-10-30 12:09:18

0

用的组合物。

创建一个类并实现迭代。该类将包装一个哈希集,并将公开添加和删除方法。您可以使用与可迭代移除相同的移除方法。