- #1
- 2,076
- 140
Homework Statement
I'm trying to override the hashcode(), equals() and compareTo() methods in a class.
Homework Equations
Java.
The Attempt at a Solution
Here's the code :
Code:
package data_cleaner;
import java.util.*;
public class SongEntry implements Comparable<SongEntry> {
private String studentNumber;
private String bookCode;
private int pageNumber;
private String songTitle;
public SongEntry(String studentNumber, String bookCode, int pageNumber, String songTitle) {
this.studentNumber = studentNumber;
this.bookCode = bookCode;
this.pageNumber = pageNumber;
this.songTitle = songTitle;
}
/*Getters and setters*/
public String getSongTitle() { return songTitle; }
public String getStudentNumber() { return studentNumber; }
public String getBookCode() { return bookCode; }
public int getPageNumber() { return pageNumber; }
public void setSongTitle(String newSongTitle) { songTitle = newSongTitle; }
@Override
/*Returns a String representation of a SongEntry*/
public String toString() {
return (studentNumber + " " + bookCode + " " + pageNumber + " " + songTitle);
}
@Override
/*Compares two songs to see if they are equal to each other by comparing song titles, book code and page numbers*/
public boolean equals(Object obj) {
if (!(obj instanceof SongEntry))
return false;
return(getBookCode().equals(((SongEntry)obj).getBookCode()) && getPageNumber() == ((SongEntry)obj).getPageNumber() && getSongTitle().equals( ((SongEntry)obj).getSongTitle()));
}
@Override
/*Retrieve the name of the song and loop through the name adding on (i+1)*ASCIIVALUE of each char
to the hashvalue which will be returned*/
public int hashCode() {
int hashValue = 0;
for(int i=0;i<getSongTitle().length();i++)
hashValue += ((int)getSongTitle().charAt(i))*(Integer.parseInt(getStudentNumber()))*(getPageNumber());
return hashValue;
}
@Override
/*Recall x.equals(y) iff x.hashcode() == y.hashcode(). Also, x.equals(y) iff x.compareTo(y) == 0.
Hence x.compareTo(y) == 0 iff x.hashcode() - y.hashcode() == 0.
This implies we can subtract the hashcode of y from x to compare each songEntry and return it.*/
public int compareTo(SongEntry aSongEntry) {
return (hashCode() - aSongEntry.hashCode());
}
}
I don't believe the methods I wrote are correct? I believe there are rules which I've missed, but I cannot see where I've made a mistake?
Last edited by a moderator: