Set集合:用于存储不重复的对象
HashSet和TreeSet是Set集合的两个实现类。
例子:
Set<Integer> set = new HashSet<Integer>();
Ramdom r = new Random();
for(int i=0; i<20; i++){
set.add(r.nextInt(100));
}
//输出结果i一般大于20次,因为重复的元素无法添加到set集合中
Set集合的遍历只能通过迭代器完成,由于其元素不和顺序下标对应。
Set<String> list = new HashSet<String>{};
list.add("one");
list.add("two");
list.add("three");
Iterator<String> it = list.iterator();
while(it.hasNext()){
String a = it.next();
System.out.println(a + " ");
}
//输出结果:Three one two
Set集合的迭代器的输出顺序与其存储结构有关,与输入顺序无关。
HashSet和HashCode
HashSet是Set集合的实现类,将对象放进HashSet集合中,需计算HashCode值来确定所存放的位置。
对于对象重写了equals方法,则也需重写HashSet方法,这样才能够使二者对应起来。

被折叠的 条评论
为什么被折叠?



