5黑马币
本帖最后由 费世福 于 2015-8-18 22:43 编辑
package it.cast.hashset;
import java.util.HashSet;
public class Test {
/**
* 要求:将Student学号003的学生的名字“ddd”换成"fff"
*
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
HashSet<Student> hashSet = new HashSet<Student>();
hashSet.add(new Student("001","qqq",18));
hashSet.add(new Student("002","aaa",14));
hashSet.add(new Student("003","ddd",13));
Student student2 = new Student(null,"fff",13);
hashSet.add(student2);
student2.setName("003");
hashSet.remove(student2);
//遍历显示
for (Student student : hashSet) {
System.out.println(student);
}
}
}
/**************************************************************************
package it.cast.hashset;
public class Student {
//成员属性
private String studentid;
private String name;
private int age;
//构造方法
public Student() {
super();
// TODO Auto-generated constructor stub
}
public Student(String name,String studentid,int age) {
super();//父类是Object
this.age = age;
this.name = name;
this.studentid = studentid;
}
//获得成员属性的get与set
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getStudentid() {
return studentid;
}
public void setStudentid(String studentid) {
this.studentid = studentid;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
//toString
@Override
public String toString() {
return "Student [studentid=" + studentid + ", name=" + name
+ ", age=" + age + "]";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
//result = prime * result + age;
result = prime * result + ((name == null) ? 0 : name.hashCode());
/*result = prime * result
+ ((studentid == null) ? 0 : studentid.hashCode());*/
return result;
}
/* @Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((studentid == null) ? 0 : studentid.hashCode());
return result;
}*/
@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;
/* if (age != other.age)
return false;*/
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
/*if (studentid == null) {
if (other.studentid != null)
return false;
} else if (!studentid.equals(other.studentid))
return false;*/
return true;
}
/*@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((studentid == null) ? 0 : studentid.hashCode());
return result;
}
@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;
if (studentid == null) {
if (other.studentid != null)
return false;
} else if (!studentid.equals(other.studentid))
return false;
return true;
}
*/
}
|
|