2

I have a set of objects and each object has its own id...

I also have a list of ids, each denoting the id of an object to be removed from the set..

Unfortunately I need the most efficient approach to do this... Obviously, I could iterate through the set, and for each entry iterate through the list to see if the ids match...

But is there a quicker way? I was wondering if it might be faster to use a Map to map ids to each object's placement within the set? It would be more to keep track of, but the efficiency here is the top priority - the set itself is dynamic and this operation will occur often...

The situation is essentially that I have a server thread that is closing sockets that another thread has determined are idle, and the server thread needs to get this done as quickly as possible, so it can resume its normal duties... Unfortunately the server thread is the only thread allowed to close sockets to avoid concurrency issues...

Are there better ways to do this?

12
  • 2
    HashMap sounds good to me, as this will allow efficient identification of the correct client connection with the small cost being the extra memory required, but let's see what others say as this is not my area of expertise. Commented Feb 12, 2014 at 19:30
  • 1
    Are we talking about a few dozen items or thousands? If either collection is smaller than a thousand, it almost certainly wouldn't be worth the overhead to build a special-purpose data structure just to reimplement removeAll(). Commented Feb 12, 2014 at 19:32
  • 1
    Premature optimization is the root of all evil Commented Feb 12, 2014 at 19:35
  • 1
    @user1121883 I think this is more an issue of code cleanliness more than optimization. At least, it should be if it's only a few dozen connections. Commented Feb 12, 2014 at 19:37
  • 1
    alrite thanks so much guys HashMap it is.. if anyone else comes up with a better way it would be interesting to know
    – matt
    Commented Feb 12, 2014 at 19:38

1 Answer 1

3

I would go with @HovercraftFullOfEels' comment.

To expand a bit:

Replace your Set with a HashMap. Use the ID of the object as the key, and the object itself as the value. Then whenever you need to remove an object, it's a simple matter of

map.remove(id);

Generally speaking, any time you need random access to any form of Collection you're probably better off using some variation of Map instead (HashMap being the most common)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.