package testForFun.demo20181109;
import java.util.HashMap;
import java.util.HashSet;
/**
* Created with IntelliJ IDEA
* User:liu
* Date:2018/11/9
* Time:14:27
*/
public class Person {
private Stringname;
private Integerage;
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
/**
* @return a hash code value for this object.
* @see Object#equals(Object)
* @see System#identityHashCode
*/
@Override
public int hashCode() {
return this.name.hashCode()+age*50;
}
/**
* @param obj the reference object with which to compare.
* @return {@code true} if this object is the same as the obj
* argument; {@code false} otherwise.
* @see #hashCode()
* @see HashMap
*/
@Override
public boolean equals(Object obj) {
if(!(objinstanceof Person)){
return false;
}
System.out.println("执行的equal方法");
Person obju = (Person) obj;
return ( obju.name==this.name&&obju.age==this.age)?true:false;
}
@Override
public String toString() {
return "Person{" +
"name='" +name +'\'' +
", age=" +age +
'}';
}
public static void main(String[] args){
Person a =new Person("张三",18);
Person b =new Person("张三",18);
a.setAge(18);
a.setName("李四");
HashSet set =new HashSet<>();
set.add(a);
set.add(b);
//只有同时重写hashCode和equal方法才能保证自定义的对象在HashSet的唯一性。
System.out.println("set集合的大小:"+set.size());
System.out.println("a的hashCode: "+a.hashCode()+", a的内容: "+a.toString());
System.out.println("b的hasnCode:"+b.hashCode()+", b的内: "+b.toString());
//-------------------------------------------------------------------//
Person person =new Person();
System.out.println(person.toString());
Person methodtest = person.methodTestThis();
System.out.println(methodtest);
}
public Person() {
//1,this 在此处表示类的实例,在构造方法中使this关键字表示调用类中的构造方法,this只能在构造方法的第一行。
this("HELLO",28);
}
public Person(String name, Integer age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
//2,this 将局部变量的值传递给成员变量
this.name = name;
}
public Person methodTestThis(){
//3,this 关键字返回这个类。还有一个重大的作用就是返回类的引用
return this;
}
}
网友评论