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

发布于 2024-10-16 02:51:53 字数 259 浏览 0 评论 0原文

我有一个 HashSet,它是客户端套接字的集合。当客户端连接时,套接字将被添加到 HashSet 中。然后我需要访问该套接字,但我不知道如何在 HashSet 中访问它。

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

我如何确定 lastAddedSocket 是什么?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

枕花眠 2024-10-23 02:51:53

无法询问 HashSet“最后添加到你身上的东西是什么?”顺序全乱了。

您应该简单地保留一个名为 lastAddedSocket 的单独变量。每次向 HashSet 添加套接字时,也将其分配给 lastAddedSocket。然后你就可以在固定的时间内轻松地查找它。

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.

梦晓ヶ微光ヅ倾城 2024-10-23 02:51:53

人们普遍认为哈希集的顺序是无法保证的。虽然 Java 文档直接指出了这一点,但 MSDN 给出的最接近的是

集合是不包含重复元素的集合,其元素没有特定的顺序。

信息感谢: HashSet 是否保留插入顺序?

也就是说,它您自己保留最后一个套接字应该相当容易。

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.

灵芸 2024-10-23 02:51:53

当您删除最后一个时,您可能希望最后一个是上一个-最后一个。我建议使用 Queue<>除了 HashSet 之外,您还可以始终记住它们到达的顺序,以防最后一个消失。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文