是集合的“ toArray”确定性的? [英] Is a set's "toArray" deterministic?

查看:64
本文介绍了是集合的“ toArray”确定性的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

很显然,集合没有任何排序方式,所以我不能期望任何特定的排序方式

Obviously, sets do not have any kind of ordering, so I cannot expect any specific ordering if I do

String[] string = mySet.toArray();

但是,我面对一个用例,我不在乎字符串数组的顺序在中,但我确实需要这样,如果两组彼此相等,则:

However, I am faced with a use case where I don't care what ordering the string array is in, but I DO need it to be the case that if two sets are equal to each other, then:

StringUtils.join(mySet.toArray(),',');

对于这些集合,无论我运行该程序多少次,都会产生相同的字符串。假设我坚持使用相同的代码。

will produce the same exact string for those sets, always, no matter how many times I run the program assuming I stick with the same code.

我有这个保证吗?

类似地,这是否真的正确?

Similarly, does this whole true for the order that elements appear for a given Set in an iterator?

推荐答案

从技术上讲,没有担保。 Set 是一个接口。实现会有所不同,并且可能会也可能不会遵循此要求。

Technically, no you don't have a guarantee. Set is an Interface. Implementations will vary and may or may not obey this requirement.

通过从Set中提取结果后对数组进行排序来强制解决问题。

Force the issue by sorting the array yourself after extracting the results from the Set.

这篇关于是集合的“ toArray”确定性的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆