set集合
作者:互联网
set集合概述:
1,set集合是一个不包含重复数据的Collection
2,set集合中的数据是无序的(因为set集合没有下标)
3,set集合中的元素不可以重复--常用来给数据去重复
4,set集合可以存储null值,最多存储一个
5,set集合去除重复的时候(泛型如果自己定义的类型的时候)你需要在自己定义的类中重写hashCode()方法和equals()方法
测试代码如下:自定义一个Student类,然后创建一个set集合对象,将创建的Student对象s1,s11,s2放入到set集合对象中
package cn.tedu.map;
import java.util.Objects;
public class Student {
private String name;
private int age;
private String tel;
public Student(String name, int age, String tel) {
this.name = name;
this.age = age;
this.tel = tel;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
", tel='" + tel + '\'' +
'}';
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getTel() {
return tel;
}
public void setTel(String tel) {
this.tel = tel;
}
@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(tel, student.tel);
}
@Override
public int hashCode() {
return Objects.hash(name, age, tel);
}
}
public class TestSet {
public static void main(String[] args) {
Set<String> set=new HashSet<>();
Set<Student> student = new HashSet<>();
Student s=new Student("张三",3,"3333");
Student s1=new Student("张三",3,"3333");
Student s2=new Student("李四",4,"4444");
student.add(s);
student.add(s1);
student.add(s2);
System.out.println(student);
}
}
最后打印的结果:
[Student{name='李四', age=4, tel='4444'}, Student{name='张三', age=3, tel='3333'}]
标签:set,tel,name,age,Student,集合,public 来源: https://www.cnblogs.com/hanmopx/p/15465063.html