set集合的学习
set集合可以去重,不能重复添加
package com.tedu.study01;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
public class Study_Set {
public static void main(String[] args) {
Set<String> s1 = new HashSet<>();
s1.add("赵玉梅");
s1.add("张飞");
s1.add("关羽");
s1.add("关心");
System.out.println(s1.size());
System.out.println(s1.isEmpty());
System.out.println(s1.contains("关羽"));
Iterator<String> iterator = s1.iterator();
for (String s : s1) {
System.out.println(s);
}
}
}
新创建的对象必须重写hashcode和equals方法才能够去重
package com.tedu.study01;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.Set;
public class Demo {
public static void main(String[] args) {
Set<Student> li = new HashSet<>();
Student s1 = new Student("赵云",19,"北京");
Student s2 = new Student("关羽",33,"南京");
Student s3 = new Student("赵云",19,"北京");
Student s4 = new Student("关羽",33,"南京");
li.add(s1);
li.add(s2);
li.add(s3);
li.add(s4);
System.out.println(li);
}
}
class Student{
private String name;
private int age;
private String addr;
public Student(){
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Student student = (Student) o;
return age == student.age &&
Objects.equals(name, student.name) &&
Objects.equals(addr, student.addr);
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
", addr='" + addr + '\'' +
'}';
}
@Override
public int hashCode() {
return Objects.hash(name, age, addr);
}
public Student(String name, int age, String addr) {
this.name = name;
this.age = age;
this.addr = addr;
}
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 String getAddr() {
return addr;
}
public void setAddr(String addr) {
this.addr = addr;
}
}