DeejUK
DeejUK

Reputation: 13501

Java - Get 'View' of Collection by Type/Interface

I need to store a number of objects in a Set. Sometimes I want to iterate over everything in the Set, and sometimes I'd like to iterate over only that implement a particular interface. Some objects will implement several of the interfaces that I want a view on.

Is there a design pattern or Guava/Java class that allows views-by-type on a Set or other collection? Preferably in the most efficient manner possible, as this code will be central to a core game loop getting called every 17 milliseconds.

Upvotes: 0

Views: 185

Answers (2)

Louis Wasserman
Louis Wasserman

Reputation: 198321

With Guava --

Sets.filter(set, Predicates.instanceOf(Foo.class));

Upvotes: 7

meirrav
meirrav

Reputation: 771

Have you thought about saving the objects in a hashtable?

Hashtable<String,Set<YourObject>> ht = new Hashtable<String,Set<YourObject>>();

Where the String is the types name. That way you can choose what to iterate over.

Upvotes: 0

Related Questions