使用equals比较,如果不同,分别输出各自内容,怎么修改程序

class Book{
 private String title;
 private int price;
 
 public Book(String title,int price){     //构造器
  this.title=title;
  this.price=price;
 }

 public String getTitle() {
  return title;
 }

 public void setTitle(String title) {
  this.title = title;
 }

 public int getPrice() {
  return price;
 }

 public void setPrice(int price) {
  this.price = price;
 }
 
 public boolean equals(Object obj){
  if(this==obj){     //比较地址是否相同
   return true;
  }
  if(obj==null){     //判断要比较的对象是否为空
   return false;
  }
  if(!(obj instanceof Book)){// 判断数据类型是否一样
   return false;
  }
  Book book=(Book) obj;  //强转数据类型
  if(this.title.equals(book.title)&&
    this.price==book.price){   //自定义比较规则
   return true;
  }else {
   return false;
  }
 
 }

 @Override
 public String toString() {
  return "Book [title=" + title + ", price=" + price + "]";
 }
 
 
}

 

public class EqualsTest {
 public static void main(String[] args) {
  Book book1=new Book("java",20);
  Book book2=new Book("java",21);
  System.out.println(book1.equals(book2));
  book1.toString();
  book2.toString();
  
 }
 
}

 

慕的地6547238
浏览 1094回答 1
1回答

Demon丶ZY

public class EqualsTest { public static void main(String[] args) {  Book book1=new Book("java",20);  Book book2=new Book("java",21);if(book1.equals(book2)){}  System.out.println(book1.toString());System.out.println( book2.toString());  } } }
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java