对于列表,我们使用该Collections.sort(List)方法.如果我们想要排序HashSet怎么办?
对于一些教程,他们说:
\n\n\n\n\nHashSet 不保持任何顺序,元素将以任何随机顺序返回。
\n
但我写了一个测试程序,结果总是一样的。
\n\nimport java.util.*;\n\npublic class HashSetDemo {\n\n public static void main(String[] args) {\n HashSet<String> hs1 = new HashSet<String>();\n hs1.add("a");\n hs1.add("b");\n hs1.add("c");\n hs1.add("d");\n hs1.add(null);\n hs1.add(null);\n System.out.println(hs1);\n System.out.println(hs1);\n }\n}\nRun Code Online (Sandbox Code Playgroud)\n\n输出:
\n\n[null, a, b, c, d]\n[null, a, b, c, d]\nRun Code Online (Sandbox Code Playgroud)\n\n我尝试了很多次,但顺序总是一样的。为什么?希望有人能帮助我,提前致谢!
\n