package haxi;
import java.util.HashSet;
public class Hashset {
public static void main(String[] args) {
// TODO 自动生成的方法存根
HashSet<Student> s1 = new HashSet<Student>();
Student student1 = new Student("yyz", 18);
Student student2 = new Student("yyzz", 18);
Student student3 = new Student("yyzzz", 18);
Student student4 = new Student("yyz", 18);
s1.add(student1);
s1.add(student2);
s1.add(student3);
for (Student string : s1) {
Student s2 = string;
System.out.println(s2.getName() + "," + s2.getAge());
}
System.out.println("此时加入重复对象yyz 18再次输出--------");
s1.add(student4);
for (Student string : s1) {
Student s2 = string;
System.out.println(s2.getName() + "," + s2.getAge());
//出现重复元素需重写原方法 放到下一段
}
}
}
class Student {
String name;
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;
}
Student(String name, int age) {
this.age = age;
this.name = name;
}
}
输出如下且相同对象可以储存
yyz,18
yyzz,18
yyzzz,18
此时加入重复对象yyz 18再次输出--------
yyz,18
yyzz,18
yyzzz,18
yyz,18
接下看重写后将不能存入相同对象(看起来
package haxi;
import java.util.HashSet;
import java.util.Objects;
public class Hashset {
public static void main(String[] args) {
// TODO 自动生成的方法存根
HashSet<Student> s1 = new HashSet<Student>();
Student student1 = new Student("yyz", 18);
Student student2 = new Student("yyzz", 18);
Student student3 = new Student("yyzzz", 18);
Student student4 = new Student("yyz", 18);
s1.add(student1);
s1.add(student2);
s1.add(student3);
for (Student string : s1) {
Student s2 = string;
System.out.println(s2.getName() + "," + s2.getAge());
}
System.out.println("此时加入重复对象yyz 18再次输出--------");
s1.add(student4);
for (Student string : s1) {
Student s2 = string;
System.out.println(s2.getName() + "," + s2.getAge());
}
}
}
class Student {
String name;
int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public int hashCode() {
return Objects.hash(age, name);
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Student other = (Student) obj;
return age == other.age && Objects.equals(name, other.name);
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
Student(String name, int age) {
this.age = age;
this.name = name;
}
}
输出如下
yyzz,18
yyz,18
yyzzz,18
此时加入重复对象yyz 18再次输出--------
yyzz,18
yyz,18
yyzzz,18
重复对象未储存
仅记录