一、Set集合的特点
Set集合的特点:
无序(存储和读取的顺序有可能不一样);
不允许重复(要求元素唯一);
没有索引。
利用HashSet存储字符串并遍历(三种遍历方法):
public static void main(String[] args) {
//创建集合对象
Set<String> set = new HashSet<String>();
//添加元素
set.add("hello");
set.add("world");
set.add("bupt");
//遍历集合对象(分为三种:数组遍历、迭代器遍历、增强for循环)
//数组遍历
Object[] objs = set.toArray();
for(int i=0; i < objs.length; i++) {
System.out.println(objs[i]);
}
//迭代器遍历
Iterator<String> it = set.iterator();
while(it.hasNext()) {
System.out.println(it.next());
}
//增强for循环遍历
for(String s : set){
System.out.println(s);
}
}
二、HashSet存储自定义对象并遍历
通过查看源码发现:
HashSet的add方法会使用当前集合中的每一个元素的Hash值与新添加元素的Hash值进行比较:如果Hash值(通过hashCode方法获取)不一样,则直接添加新的元素;如果Hash值一样,则比较比较地址值或者使用元素中重写的equals方法进行比较,若比较结果一样,则认为元素重复,不再添加,若比较结果不一样,则可以添加。
public class test {
public static void main(String[] args) {
//创建集合对象
HashSet<Student> set = new HashSet<Student>();
//创建自定义类对象
Student s0 = new Student("hxf2",20);
Student s1 = new Student("hxf",18);
Student s2 = new Student("hxf1",19);
Student s3 = new Student("hxf2",20);
//将自定义类对象添加到集合中
set.add(s1);
set.add(s2);
set.add(s3);
for(Student s : set){
//增强for循环遍历集合
System.out.println(s);
System.out.println(s.hashCode());
}
}
}
class Student{
private String name;
private int age;
public Student(String name, int age) {
//构造方法,为了初始化
this.name = name;
this.age = age;
}
@Override
public String toString() {
//使用Eclipse自动生成,用于显示自定义类Student的成员变量
return "Student [name=" + name + ", age=" + age + "]";
}
&#