package examples; import java.util.*; import java.text.*; /** * CS401 Example AbstractCD * * * * @author PJ Dillon */ public abstract class AbstractCD implements Comparable { public final static String [] music_genres = {"Popular", "Rock", "Jazz", "Country", "R&B", "Classical", "Other"}; private String title; private int genre; private Date releaseDate; private int length; // in seconds protected String[] trackTitles; public AbstractCD(String title, int genre, String date, int length, String[] titles) { this.title = title; this.genre = genre; this.length = length; trackTitles = new String[titles.length]; for(int i = 0; i < titles.length; i++) trackTitles[i] = titles[i]; DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT); try { releaseDate = df.parse(date); } catch(ParseException pe) { releaseDate = null; } } /** * Inherited from Object */ public String toString() { StringBuffer S = new StringBuffer(); S.append("CD: " + title + "\n"); S.append("Genre: " + music_genres[genre] + "\n"); if (releaseDate != null) { S.append("Release Date: " + releaseDate.toString() + "\n"); } else { S.append("No release date \n"); } int min = length / 60; int sec = length % 60; S.append("Number of tracks: " + trackTitles.length + "\n"); S.append("Length: " + min + " min. " + sec + " sec. \n"); return S.toString(); } /** * Here we override the equals() method inherited from the Object class. * Recall that equals() must be reflexive, symmetric, and transitive. */ public boolean equals(Object o) { if(o == null) return false; if(o instanceof AbstractCD) { System.out.println("this: " + getClass() + " o: " + o.getClass()); AbstractCD cd = (AbstractCD) o; return title.equals(cd.title); } return false; } /** * Since equals() is overridden, it's good practice to also override * hashCode(). The equals() method only compares the CD titles; so that, in * order to maintain the contract that if equals() returns true, hashCode() * returns the same hash value, we simply have to return the hash code of the * String title with the assumption that the String class implemented a * hashCode() method under the same contract. */ public int hashCode() { return title.hashCode(); } public int compareTo(AbstractCD rhs) { return title.compareTo(rhs.title); } }