Set集合的特点:
目录
1,无序
2,元素不能重复
Set集合的两种遍历方式:
1,foreach
//1.foreach
for (Object object : set) {
System.out.println(object);
}
2,迭代器
Iterator iterator = set.iterator();
while(iterator.hasNext()) {
Object next = iterator.next();
System.out.println(next);
}
常用实现类(HashSet)
public static void main(String[] args) {
Set<String> set = new TreeSet<String>();
//根据某种规则对里面的元素进行排序
set.add("李江");
set.add("罗骁");
set.add("f");
set.add("b");
set.add("d");
for (String string : set) {
System.out.println(string);
}
效果图
比较器(hashCode)
public static void main(String[] args) {
Set<User> set = new TreeSet<User>(new NameComeparator());
//根据某种规则对里面的元素进行排序
set.add(new User(1,"a","女"));
set.add(new User(3,"z","不详"));
set.add(new User(2,"f","妖"));
set.add(new User(3,"a","女"));
for (User user : set) {
System.out.println(user);
}
}
效果图