I have a class, Cast(as in cast of a play), that implements the Collection<Actor> interface(Actor is a class representing an entity in a game) and I have the following code.
Set<Actor> toRemove = new HashSet(locations.keySet());
//method 1
toRemove.removeAll(actors);
//method 2
for(Actor actor : actors){
toRemove.remove(actor);
}
if I use method 1 nothing gets removed from the toRemove set, but method 2 does just what I want. I'm doing fine with method 2 but I'm curious why 1 doesn't work. This is the Cast class.
package Felidae.Actors;
import Felidae.Physics.*;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.List;
import java.util.LinkedList;
public class Cast implements Collection<Actor> {
private List<Actor> actorList;
private Map<String, Actor> actorMap;
public Cast(){
actorList = new LinkedList<Actor>();
actorMap = new HashMap<String, Actor>();
}
public int size() {
return actorList.size();
}
public boolean isEmpty() {
return actorList.isEmpty();
}
public boolean contains(Object o) {
if(o instanceof Actor){
return actorList.contains((Actor)o);
}else{
return false;
}
}
public Iterator iterator() {
return actorList.iterator();
}
public Object[] toArray() {
return actorList.toArray();
}
public Object[] toArray(Object[] a) {
return actorList.toArray(a);
}
public boolean add(Actor o) {
actorMap.put(o.name, o);
return actorList.add(o);
}
public boolean remove(Object o) {
if(o instanceof Actor){
Actor a = (Actor)o;
if(!a.name.isEmpty()){
actorMap.remove(a.name);
}
return actorList.remove(a);
}else{
return false;
}
}
public boolean containsAll(Collection c) {
return actorList.containsAll(c);
}
public boolean addAll(Collection c) {
boolean result = actorList.addAll(c);
for(Object o : c){
if(o instanceof Actor){
Actor a = (Actor)o;
if(!a.name.isEmpty()){
actorMap.put(a.name, a);
}
}
}
return result;
}
public boolean removeAll(Collection c) {
boolean result = actorList.removeAll(c);
for(Object o : c){
if(o instanceof Actor){
Actor a = (Actor)o;
if(!a.name.isEmpty()){
actorMap.remove(a.name);
}
}
}
return result;
}
public boolean retainAll(Collection c) {
return actorList.retainAll(c);
}
public void clear() {
actorList.clear();
}
public Actor get(String name){
return actorMap.get(name);
}
}