public class SetDemo {
public static void main(String[] args) {
//创建集合对象
Set set=new HashSet<>();
//添加元素
set.add("hello");
set.add("world");
set.add("java");
//不包含重复元素
set.add("java");
//遍历
for (String s: set) {
System.out.println(s);
}
}
}
哈希值
public class Student {
public String name;
public int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
public class SetDemo2 {
public static void main(String[] args) {
//创建学生对象
Student student=new Student();
student.setAge(18);
student.setName("lisi");
//同一个对象多次调用hashCode()方法返回值是相同的
System.out.println(student.hashCode());//460141958
System.out.println(student.hashCode());//460141958
Student student1=new Student();
student1.setName("lisi");
student1.setAge(18);
//默认情况下,不同对象的哈希值不同(可以在Student类中重写hashCode()方法,这时候结果相同)
System.out.println(student1.hashCode());//1163157884
System.out.println("hello".hashCode());//99162322
System.out.println("java".hashCode());//3254818
}
}
想想为什么"java"和"hello"都有哈希值,并且不同(自己找资料查找)
HashSet集合特点public class HashSetDemo1 {
public static void main(String[] args) {
HashSet hashSet=new HashSet();
//添加元素
hashSet.add("hello");
hashSet.add("world");
hashSet.add("java");
//遍历输出
for (String s: hashSet) {
System.out.println(s);
}
}
}
HashSet集合保证元素唯一分析
LinkedHashSet集合特点
public class LinkedHashSetDemo {
public static void main(String[] args) {
LinkedHashSet list=new LinkedHashSet<>();
//添加元素
list.add("hello");
list.add("world");
list.add("java");
list.add("java");
System.out.println(list);
for (String s: list) {
System.out.println(s);
}
}
}
TreeSet集合的特点
public class TreeSetDemo {
public static void main(String[] args) {
TreeSet set=new TreeSet<>();
//添加元素
set.add(10);
set.add(25);
set.add(14);
set.add(14);
System.out.println(set);
for (Integer i: set) {
System.out.println(i);
}
}
}
自然排序的Comparable的使用
public class Student implements Comparable{
public String name;
public int age;
public String getName() {
return name;
}
public int getAge() {
return age;
}
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public Student(){}
@Override
public int compareTo(Object o) {
return 1;
}
}
public class TreeSetDemo2 {
public static void main(String[] args) {
//创建集合对象
TreeSet set=new TreeSet();
//创建学生集合对象
Student student1=new Student("lisi",18);
Student student2=new Student("zhangsan",20);
Student student3=new Student("maliu",30);
Student student4=new Student("wangwu",40);
//把学生添加到集合中
set.add(student1);
set.add(student2);
set.add(student3);
set.add(student4);
for (Student s: set) {
System.out.println(s.getName()+","+s.getAge());
}
}
}
如果compareTo()方法返回的是0,则只打印一个结果
如果compareTo()方法返回的是-1,则逆着打印一个结果



