fork(1) download
  1. import java.util.*;
  2.  
  3. class Book implements Comparable<Book>, Cloneable {
  4. /* private */ String title;
  5. /* private */ Date publishDate;
  6. /* private */ String comment;
  7.  
  8. public boolean equals(Object obj) {
  9. if(obj == this) return true;
  10. if(obj == null) return false;
  11. if(!(obj instanceof Book)) return false;
  12. Book result = (Book) obj;
  13. if(!result.title.equals(this.title)) return false;
  14. if(!result.publishDate.equals(this.publishDate)) return false;
  15. return true;
  16. }
  17.  
  18. public int hashCode() {
  19. int hash = 1;
  20. hash = hash * 31 + title.hashCode();
  21. hash = hash * 31 + publishDate.hashCode();
  22. return hash;
  23. }
  24.  
  25. public int compareTo(Book obj) {
  26. return this.publishDate.compareTo(obj.publishDate);
  27. }
  28.  
  29. public Book clone() {
  30. Book result = new Book();
  31. result.title = this.title;
  32. result.comment = this.comment;
  33. result.publishDate = (Date) this.publishDate.clone();
  34. return result;
  35. }
  36. }
  37.  
  38. public class Main {
  39. public static void main(String[] args) {
  40. Book book1 = new Book();
  41. book1.title = "本1";
  42. book1.publishDate = new Date(1);
  43. Book book2 = new Book();
  44. book2.title = "本1";
  45. book2.publishDate = new Date(1);
  46. boolean bool1 = book1.equals(book2);
  47. System.out.println(bool1);
  48.  
  49. Book book3 = new Book();
  50. book3.title = "本2";
  51. book3.publishDate = new Date();
  52. Book book4 = new Book();
  53. book4.title = "本2";
  54. boolean bool2 = book3.equals(book4);
  55. System.out.println(bool2);
  56. // System.out.println(book4.publishDate);
  57. }
  58. }
Runtime error #stdin #stdout #stderr 0.1s 27876KB
stdin
Standard input is empty
stdout
true
stderr
Exception in thread "main" java.lang.NullPointerException
	at Book.equals(Main.java:14)
	at Main.main(Main.java:54)