import java.util.*;public class HashSetDemo02 {
public static void main(String[] args) {
Set<Person> allset = new HashSet<Person>();
allset.add(new Person("张三",20));
allset.add(new Person("李四",21));
allset.add(new Person("李四",21));
allset.add(new Person("李四",21));
allset.add(new Person("李四",21));
System.out.println(allset);
}}
Person {
private String name;
private int age;
public Person(String name, int age) {
this.setName(name);
this.setAge(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;
}
//覆写equels()方法和hashCode()方法
public boolean equels(Object obj){
if(this == obj){
return true;
}
if(!(obj instanceof Person)){
return false;
}
Person p = (Person)obj;
if(this.name.equals(p.name) && this.age == p.age){
return true;
}else{
return false;
}
}
public int hashCode(){
return this.name.hashCode()*this.age;//指定公式
}
public String toString(){
return "姓名:" + this.getName() + "年龄:" + this.getAge();
}
}覆写了Object的equels()和hashCode()方法,可以去掉重复元素,可是结果没有去掉,为什么?
public static void main(String[] args) {
Set<Person> allset = new HashSet<Person>();
allset.add(new Person("张三",20));
allset.add(new Person("李四",21));
allset.add(new Person("李四",21));
allset.add(new Person("李四",21));
allset.add(new Person("李四",21));
System.out.println(allset);
}}
Person {
private String name;
private int age;
public Person(String name, int age) {
this.setName(name);
this.setAge(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;
}
//覆写equels()方法和hashCode()方法
public boolean equels(Object obj){
if(this == obj){
return true;
}
if(!(obj instanceof Person)){
return false;
}
Person p = (Person)obj;
if(this.name.equals(p.name) && this.age == p.age){
return true;
}else{
return false;
}
}
public int hashCode(){
return this.name.hashCode()*this.age;//指定公式
}
public String toString(){
return "姓名:" + this.getName() + "年龄:" + this.getAge();
}
}覆写了Object的equels()和hashCode()方法,可以去掉重复元素,可是结果没有去掉,为什么?
解决方案 »
- Process的Runtime.getRuntime().exec执行linux,cd命令问题
- 求教,在linux下调试程序的方法。
- 关于java
- 菜鸟 首次提问 高手多多指教???!!!
- 求一正则表达式
- 关于串口读取数据是丢失的问题!请教各位~~~
- 菜鸟求教菜单项:快捷键(十万火急)
- 求助,用java读入图片,转换成黑白,在图片中放入密码,转换成其它模糊图片,再把图像模糊处理.
- 再java中这么播放媒体软件(在知道媒体软件路径得情况下)
- 在red hat 7.0或sco unix5.0下jdk的安装?
- 我下载了一个信息管理系统的JAVA程序,如何打开,打包成ZIP。
- 我要做一个学生管理系统,请问下具体步骤和操作
public boolean equals(Object obj){ //---是equals而不是equels
if(this == obj){
return true;
}
if(!(obj instanceof Person)){
return false;
}
Person p = (Person)obj;
if(this.name.equals(p.name) && this.age == p.age){
return true;
}else{
return false;
}
}