Friday, February 6, 2015

Comparable

The compareTo method of the class is defining the "natural" ordering of that object. That method is contractually obligated (though not demanded) to be in line with other methods on that object, such as a 0 should always be returned for objects when the .equals() comparisons return true. compareTo method must be implemented in the class for which object is sorting. Disadvantage is that you have imlement Comparable interface and override compareTo method. If it is not possible, then we have to extend the class.

Song.java



package com.parvez.albumCollection;
public class Song implements Comparable<Song>{
    public Song(String t,String a,int r)
    {
        setArtist(a);
        setRanking(r);
        setTitle(t);
    }
    private String title;
    private String artist;
    private int ranking;

    public String getTitle() {
        return title;
    }

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

    public String getArtist() {
        return artist;
    }

    public void setArtist(String artist) {
        this.artist = artist;
    }

    public int getRanking() {
        return ranking;
    }

    public void setRanking(int ranking) {
        this.ranking = ranking;
    }

    @Override    public int compareTo(Song o) {
        return this.getTitle().compareTo(o.getArtist());
    }

    public String toString()
    {
        return "Title: "+ this.getTitle() + " Artist: " +getArtist() +" Ranking: " + getRanking();
    }
}

AlbumSongs.java

package com.parvez.albumCollection;

import java.io.*;
import java.util.ArrayList;
import java.util.Collections;


public class AlbumSongs {
    ArrayList<Song> songs=new ArrayList<Song>();
    public static void main(String[] args)
    {
        AlbumSongs album=new AlbumSongs();
        album.getSongs();
        album.displaySongs();
        System.out.println();
        Collections.sort(album.songs);

    }

    private void displaySongs() {
        for (Song song: songs)
        {
            System.out.println(song.toString());
        }
    }

    private void getSongs() {
        File file;
        BufferedReader bufferedReader;

        try        {
            file=new File("input.txt");
            bufferedReader=new BufferedReader(new FileReader(file));

            String line;
            while((line=bufferedReader.readLine())!=null)
            {
                String[] lineString=line.split(",");
                Song aSong=new Song(lineString[1],lineString[0],Integer.parseInt(lineString[2]));
                songs.add(aSong);
            }
        }
        catch (FileNotFoundException e)
        {
            e.printStackTrace();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }


}



No comments:

Post a Comment