Hello, I am studying the book Head First Java and have come up with an example using a comparator in collections. Example from the book:
package Jukebox3; import java.io.*; import java.util.*; class Song { String title; String artist; String rating; String bpm; public int compareTo(Song s) { return title.compareTo(s.getTitle()); } Song(String t, String a, String r, String b) { title = t; artist = a; rating = r; bpm = b; } public String getTitle() { return title; } public String getArtist() { return artist; } public String getRating() { return rating; } public String getBpm() { return bpm; } public String toString() { return title; } } public class Jukebox3 { ArrayList<Song> songList = new ArrayList<>(); public static void main(String[] args) { new Jukebox3().go(); } class ArtistCompare implements Comparator<Song> { public int compare(Song one, Song two) { return one.getArtist().compareTo(two.getArtist()); } } public void go() { getSongs(); ArtistCompare artistCompare = new ArtistCompare(); Collections.sort(songList, artistCompare); System.out.println(songList); } void getSongs() { try { File file = new File("SongList.txt"); BufferedReader reader = new BufferedReader(new FileReader(file)); String line = null; while((line = reader.readLine()) != null) { addSong(line); } }catch(Exception e) { e.printStackTrace(); } } void addSong(String lineToParse) { String[] tokens = lineToParse.split("/"); Song nextSong = new Song(tokens[0], tokens[1], tokens[2], tokens[3]); songList.add(nextSong); } } How this method works:
void addSong(String lineToParse) { String[] tokens = lineToParse.split("/"); Song nextSong = new Song(tokens[0], tokens[1], tokens[2], tokens[3]); songList.add(nextSong); } We have 5 lines in the file, we divide these five lines into 4 parts and add them to the array. Next, create a new Song object and add it to the ArrayList<Song> collection. And since the lines in file 5, then the objects in the collection will also be respectively 5. Did I understand correctly in this place?
Next comes the comparator:
class ArtistCompare implements Comparator<Song> { public int compare(Song one, Song two) { return one.getArtist().compareTo(two.getArtist()); } } He compares 2 objects, but we have 5 objects, how does he compare the rest? Help please, very tight comes: (