JAvaSE(04)(equalsメソッド)
Equalsメソッドと"=="の詳細
:
package zz.itheima.equals;
//
public class Animal {
/** * 1.equals object , ( ) ( ) * 2. * 3. equals */
private String name;
private 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;
}
public Animal(String name, int age) {
super();
this.name = name;
this.age = age;
}
public Animal() {
super();
}
//equals ( )
public boolean equals(Object o){
//1. ,
//2、this , animal,==
if (this==o) {
return true;
}else {//
if(o instanceof Animal){//
//
Animal other = (Animal)o;//
if (this.name.equals(other.getName())&&this.age==other.getAge()) {
return true;
}else {
return false;
}
}else {//
return false;
}
}
}
}
package zz.itheima.equals;
//
public class Book {
private String name;
private double price;
private int isbn;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public int getIsbn() {
return isbn;
}
public void setIsbn(int isbn) {
this.isbn = isbn;
}
public Book(String name, double price, int isbn) {
super();
this.name = name;
this.price = price;
this.isbn = isbn;
}
public Book() {
super();
}
// hashcode
public int hashCode(){
return isbn + name.hashCode() + (int )price;
}
// toString
public String toString(){
return "isbn" + isbn + " :" + name + " :" + price;
}
}
package zz.itheima.equals;
public class TestAnimal {
public static void main(String[] args) {
/** * 1.== , , ==, , * , , 。 * */
int j1 = 10;
int j2 = 10;
Animal a1 = new Animal();
a1.setName("a");
Animal a2 = new Animal();
a2.setName("a");
Animal a3 = a1;
System.out.println(j1==j2);// true;
System.out.println(a1==a2);//a1 a2 , , false
System.out.println(a1==a3);// a1 a3, true
System.out.println(a1.equals(new Book()));// false;
}
}
package zz.itheima.equals;
public class TestBook {
public static void main(String[] args) {
// hashcode
Book b1 = new Book("aaa", 10.0, 1);
Book b2 = new Book("aaa", 10.0, 1);
System.out.println(b1.hashCode());//
System.out.println(b2.hashCode());//hashcode ( @ ), hashcode。
}
}
//
package zz.itheima.equals;
public class TestGetCalss {
public static void main(String[] args) {
//
Book b = new Book();
Class c = b.getClass();
System.out.println(c.getName());// :zz.itheima.equals.Book
}
}
// toString
package zz.itheima.equals;
public class TesttoString {
public static void main(String[] args) {
// toString()
Animal animal = new Animal();
System.out.println(animal);// @ 。
}
}