2

I have a HashSet that is a collection of client sockets. When a client connects, the socket is added to the HashSet. I then need to access that socket, but I don't know how to access it in the HashSet.

... 
clientSockets.Add(listenerSocket.EndAccept(async));
WaitForData(lastAddedSocket);
....

How could I determine what lastAddedSocket is?

John Saunders
  • 160,644
  • 26
  • 247
  • 397
Booers
  • 351
  • 4
  • 8
  • 1
    There's no order in a HashSet. – Austin Salonen Feb 08 '11 at 02:05
  • I think you should actually use Stack generic. http://msdn.microsoft.com/en-us/library/3278tedw.aspx. HashSet is to make sure you won't add duplicated objects. I don't see how HashSet<> brings any value to you here. – Harvey Kwok Feb 08 '11 at 02:21
  • @Harvey Kwok It depends on what the author intended. If they truly only want to know the last socket added (for the purpose of calling `WaitForData`), and subsequently treat all sockets as peers in a set, then it makes perfect sense to store them in a "set" data type (such as HashSet), and use a local variable to track the currently-being-inserted socket. It isn't just about preventing duplication; it's imposing a semantics which boldly states "the order of these sockets is not important". The semantics of a Stack implies that you will only *ever* refer to the most recently-added socket. – mgiuca Feb 08 '11 at 03:00
  • @mgiuca true - perhaps, he is trying to just hold a reference to it by using `HashSet`. I don't know but it looks weird to me anyway :) – Harvey Kwok Feb 08 '11 at 03:14
  • possible duplicate of [Does HashSet preserve insertion order?](http://stackoverflow.com/questions/657263/does-hashset-preserve-insertion-order) – Cody Gray - on strike Feb 08 '11 at 06:44

3 Answers3

7

There is no way to ask a HashSet "what was the last thing that was added to you?" The order is all jumbled up.

You should simply keep a separate variable called lastAddedSocket. Every time you add a socket to the HashSet, also assign it to lastAddedSocket. Then you will be able to look it up easily and in constant time.

mgiuca
  • 20,958
  • 7
  • 54
  • 70
2

It is generally understood that a hashset's order is not guaranteed. While the Java documentation comes right out and says this the closest the MSDN comes is

A set is a collection that contains no duplicate elements, and whose elements are in no particular order.

Information thanks to: Does HashSet preserve insertion order?

That said, it should be fairly easy for you to preserve your last socket yourself.

Community
  • 1
  • 1
Spencer Ruport
  • 34,865
  • 12
  • 85
  • 147
0

You will probably want your last to be previous-last when you delete the last one. I recommend using Queue<> in addition to the HashSet so you will be able always remember the sequence in which they arrived, in case that last goes away.

Daniel Mošmondor
  • 19,718
  • 12
  • 58
  • 99