简体   繁体   English

如何访问添加到HashSet的最后一个对象?

[英]How can I access the last object added to a HashSet?

I have a HashSet that is a collection of client sockets. 我有一个HashSet,它是客户端套接字的集合。 When a client connects, the socket is added to the HashSet. 当客户端连接时,套接字将添加到HashSet。 I then need to access that socket, but I don't know how to access it in the HashSet. 然后我需要访问该套接字,但我不知道如何在HashSet中访问它。

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

How could I determine what lastAddedSocket is? 我怎样才能确定lastAddedSocket是什么?

There is no way to ask a HashSet "what was the last thing that was added to you?" 没有办法问HashSet“你最后添加的东西是什么?” The order is all jumbled up. 订单全都混乱了。

You should simply keep a separate variable called lastAddedSocket . 您应该只保留一个名为lastAddedSocket的单独变量。 Every time you add a socket to the HashSet, also assign it to lastAddedSocket . 每次向HashSet添加套接字时,也将其分配给lastAddedSocket Then you will be able to look it up easily and in constant time. 然后,您将能够在不断的时间内轻松查找。

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 虽然Java文档出来了,并且说这与MSDN最接近

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? 信息归功于: HashSet是否保留了插入顺序?

That said, it should be fairly easy for you to preserve your last socket yourself. 也就是说,你自己保留最后一个插座应该相当容易。

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. 我建议除了HashSet之外还使用Queue <>,这样你就可以永远记住它们到达的顺序,以防最后消失。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM