Results 1 to 3 of 3
- 10-26-2009, 06:54 PM #1
Member
- Join Date
- Oct 2008
- Location
- Washington, US
- Posts
- 28
- Rep Power
- 0
ArrayLists compareTo method, equals method
Hi, I'm having a little bit of trouble with my compareTo and equals methods. I have implemented Comparable<Book>. The assignment is to Create a library of books and with each book has a title and an ArrayList of authors. The compareTo method should base the comparison on the title field. This is what I have so far:
The equals method should compare Books base on their title and authors. This is what I have so far:Java Code:public int compareTo(Book other) { return myTitle.compareTo(other.myTitle) ; }
I have not implemented the authors in the equals method, have not gone that far with it.Java Code:public boolean equals(Object o) { boolean flag = false ; Book book = (Book) o ; if (book.myTitle == myTitle) { flag = true ; } return flag ; }
I sort of understand what the compareTo method and equals method is doing, but not really at the same time. If anybody can shine some light on this. Thank You.
- 10-26-2009, 07:13 PM #2
Member
- Join Date
- Oct 2009
- Posts
- 25
- Rep Power
- 0
Having a class implement Comparable means that instance of that class can have some sort of order. In your case, your Book objects are ordered alphabetically based on their title. Read the API for Comparable for more information on how that works.
Overriding equals imposes an equality on two different objects. That is in your case, a Book is equivalent to another Book if the title and the list of authors is the same.
For example:
Java Code:Book book1 = new Book(); // title = "Book Title 1"; author = "John Smith"; Book book2 = new Book(); // title = "Book Title 2"; author = "Jane Doe"; Book book3 = new Book(); // title = "Book Title 1"; author = "John Smith"; book1 == book1 // true book1 == book2 // false book1.equals(book2) // false book1.equals(book3) // true book1 == book3 // false
Last edited by literallyjer; 10-26-2009 at 07:27 PM.
- 10-26-2009, 07:20 PM #3
Member
- Join Date
- Oct 2008
- Location
- Washington, US
- Posts
- 28
- Rep Power
- 0
Similar Threads
-
Create code for Binary Search Tree using compareTo method using I/O
By harvin23 in forum New To JavaReplies: 5Last Post: 10-13-2009, 01:35 PM -
equals method
By mani_miit in forum Advanced JavaReplies: 7Last Post: 09-09-2009, 10:26 PM -
[SOLVED] Sorting / compareTo method confusion. Please help
By kbullard516 in forum New To JavaReplies: 8Last Post: 03-19-2009, 09:38 PM -
equals method
By timkd127 in forum New To JavaReplies: 2Last Post: 01-24-2009, 06:52 PM -
how compareTo Method works
By nanaji in forum Advanced JavaReplies: 1Last Post: 06-22-2008, 07:40 PM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks