英文:
Why the HashSet add the Objects not in the order as in the code?
问题
以下是您提供的代码的翻译部分:
import java.util.*;
public class SetDemo {
public static void main(String[] args) {
// TODO Auto-generated method stub
HashSet<String> s1 = new HashSet<String>();
s1.add("Java");
s1.add("C++");
s1.add("C");
s1.add("dotNet");
s1.add("JavaScript");
s1.add("Script");
s1.add("Python");
s1.add("JavaScript");
}
}
输出结果为:
[Java, Script, C++, dotNet, C, JavaScript, Python]
英文:
This is what i tried.
import java.util.*;
public class SetDemo {
public static void main(String[] args) {
// TODO Auto-generated method stub
HashSet<String> s1=new HashSet<String>();
s1.add("Java");
s1.add("C++");
s1.add("C");
s1.add("dotNet");
s1.add("JavaScript");
s1.add("Script");
s1.add("Python");
s1.add("JavaScript");
}
}
Output
[Java, Script, C++, dotNet, C, JavaScript, Python]
Edit:Just read this , i think it might be answer to what i was asking
答案1
得分: 6
来自相关的 JavaDoc:
这个类实现了 Set 接口,由哈希表(实际上是 HashMap 实例)支持。它不保证集合的迭代顺序;特别地,它不保证顺序会随时间保持恒定。这个类允许 null 元素。
基本上,一个 HashSet:
- 存储唯一的元素并允许 null
- 由 HashMap 支持
- 不保持插入顺序
- 不是线程安全的
英文:
From the relevant JavaDoc:
> This class implements the Set interface, backed by a hash table
> (actually a HashMap instance). It makes no guarantees as to the
> iteration order of the set; in particular, it does not guarantee that
> the order will remain constant over time. This class permits the null
> element.
Basically, a HashSet:
- stores unique elements and permits nulls
- is backed by a HashMap
- doesn't maintain insertion order
- is not thread-safe
答案2
得分: 2
你需要使用 LinkedHashSet<>()
来实现相同的功能。
import java.util.*;
public class SetDemo {
public static void main(String[] args) {
// TODO Auto-generated method stub
LinkedHashSet<String> s1 = new LinkedHashSet<String>();
s1.add("Java");
s1.add("C++");
s1.add("C");
s1.add("dotNet");
s1.add("JavaScript");
s1.add("Script");
s1.add("Python");
s1.add("JavaScript");
}
}
如果你想要自然顺序,也可以使用 SortedSet
。
英文:
You need you to use LinkedHashSet<>()
for the same.
import java.util.*;
public class SetDemo {
public static void main(String[] args) {
// TODO Auto-generated method stub
HashSet<String> s1=new LinkedHashSet<String>();
s1.add("Java");
s1.add("C++");
s1.add("C");
s1.add("dotNet");
s1.add("JavaScript");
s1.add("Script");
s1.add("Python");
s1.add("JavaScript");
}
}
You can also use the SortedSet
if you want natural order.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论