目录
- set接口的使用
- 特点:无序。没有下标,不能重复
public class Person implements Comparable<Person>{
private int age;
private String name;
public Person() {
}
public Person(String name,int age) {
this.age = age;
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Person{" +
"age=" + age +
", name='" + name + '\'' +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Person person = (Person) o;
return age == person.age && Objects.equals(name, person.name);
}
@Override
public int hashCode() {
return Objects.hash(age, name);
}
//先按性比,在按年龄比
@Override
public int compareTo(Person o) {
int n1=this.getName().compareTo(o.getName());
int n2=this.getAge()-o.getAge();
return n1==0?n2:n1;
}
public static void main(String[] args) {
//创建集合
HashSet<String> set=new HashSet<>();
//添加数据
set.add("1");
set.add("2");
set.add("3");
//移除数据
set.remove("1");
System.out.println(set.toString());
System.out.println("数据的个数"+set.size());
System.out.println(set.toString());
//遍历数据
System.out.println("====================3.2 增强for循环=====================");
for(String i:set){
System.out.println(i);
}
System.out.println("====================3.2 Iterator迭代器=====================");
//3.2 Iterator迭代器
Iterator<String> it=set.iterator();
while (it.hasNext()){
//不能使用Collection删除
String s=(String)it.next();
System.out.println(s);
//it.remove();
}
//* 4、判断
System.out.println(set.contains("张三"));
System.out.println(set.isEmpty());
}
存储过程
1、根据hascode计算保存的位置,如果为空,则直接保存,不为空执行第二步
2、在执行equal方法,如果equals方法为true,则认为重复,否则,形成链表
public static void main(String[] args) {
HashSet<Person> peoples=new HashSet<>();
Person p1=new Person("刘德华",20);
Person p2=new Person("李小龙",22);
Person p3=new Person("彭于晏",24);
peoples.add(p1);
peoples.add(p2);
peoples.add(p3);
//在person中重写hascode和equals方法后,不能添加Person("彭于晏",24),应为重复了
peoples.add(new Person("彭于晏",24));
//如果没重写equals是不能删除的
peoples.remove(new Person("刘德华",20));
System.out.println("数据的个数"+peoples.size());
System.out.println(peoples.toString());
}