问题
I tried running the following code across multiple Julia REPL sessions, on MacOSX and Linux, and the outputs were always exactly the same (in the same order):
julia> (Set([1, 2, 3, 4]), Dict(1=>2, 3=>4, 5=>6))
(Set([4, 2, 3, 1]), Dict(3 => 4,5 => 6,1 => 2))
Question: is this behavior guaranteed by the language, across sessions, platforms and versions, and for all hash-based collections?
Notes:
- I understand that the output order may vary depending on the insertion order, especially if there are hash collisions. My question assumes that the insertion order is constant.
- This question is related to my other question about the stability of the
hash()
function itself (it's closely related, but different).
回答1:
No, this is part of the internal implementation and as always with internal things, developers do not guarantee that order behaviour will be the same across various platforms and versions.
At the same time, if you want to have Set
or Dict
structure with guaranteed order, you can use either OrderedCollections.jl or Dictionaries.jl which preserve order. Regarding the dictionaries, you may also read this and this topics, because they have other nice features other than order preservation.
来源:https://stackoverflow.com/questions/62461860/is-the-order-of-julia-sets-and-dicts-guaranteed-to-be-stable-across-sessions-pl