Frage

Below I pasted the whole code.

For each line of text in dvdinfo.txt we read, we are creating new instance of DVDInfo class and storing it in the ArrayList. As of now consider that this class doesn't implement any interface and in main method not use any sort method. So in that criteria, when we print the dvdList arraylist it printsout everything as in the file without sorting. My first doubt is that how the new instance stored in ArrayList prints the text correctly, where we did not use any getter method to store the text as it is in ArrayList.

Now consider the whole code that it implements the comparable interface and collections.sort() in main.

The compareTo() method returns an int with the following characteristics:
* negative if thisObject < anotherObject 
* zero If thisObject == anotherObject 
* positive If thisObject > anotherObject 
    Wrote in SCJP by Kathy/Bates

In the below code it implements compareTo() method. How a call happens to this compareTo() from sort and how this int values are helpful for sort method to sort the objects. How it works when we compare only title object with that and how the sorting occurs. How does that collections.sort(dvdlist) jointly works with this compareTo() method?

dvdinfo.txt

Donnie Darko/sci-fi/Gyllenhall, Jake
Raiders of the Lost Ark/action/Ford, Harrison
2001/sci-fi/??
Caddy Shack/comedy/Murray, Bill
Star Wars/sci-fi/Ford, Harrison
Lost in Translation/comedy/Murray, Bill
Patriot Games/action/Ford, Harrison

MyDVD.java

import java.util.*;
import java.io.*;

class DVDInfo implements Comparable<DVDInfo>{
    String title;
    String genre;
    String leadActor;

    DVDInfo(String t, String g, String a){
        title = t; genre = g; leadActor = a;
    }

    public String toString(){
        return title + " " + genre + " " + leadActor + "\n";
    }

    public int compareTo(DVDInfo d){
        return title.compareTo(d.getTitle());
    }

    public String getTitle(){
        return title;
    }

    public String getGenre(){
        return genre;
    }

    public String getLeadActor(){
        return leadActor;
    }

    public void setTitle(String t){
        title = t;
    }

    public void setGenre(String g){
        genre = g;
    }
    public void setLeadActor(String l){
        leadActor = l;
    }


}

public class MyDVD{
    public static void main(String[] args){
        ArrayList<DVDInfo> dvdList = new ArrayList<DVDInfo>();
        populateList(dvdList);

        Collections.sort(dvdList);
        System.out.println(dvdList);

    }

    public static void populateList(ArrayList<DVDInfo> dvdList){
        try{    
            File file = new File("dvdinfo.txt"); 
            FileReader fr = new FileReader(file);
            BufferedReader br = new BufferedReader(fr);

            String s;
            while ((s = br.readLine()) != null){
                String[]tokens = s.split("/");
                dvdList.add(new DVDInfo(tokens[0],tokens[1],tokens[2]));
            }
            br.close();
        }catch(IOException e){System.out.println("File doesn\'t exist");}

    }

}

Output:

[2001 sci-fi ??
, Caddy Shack comedy Murray, Bill
, Donnie Darko sci-fi Gyllenhall, Jake
, Lost in Translation comedy Murray, Bill
, Patriot Games action Ford, Harrison
, Raiders of the Lost Ark action Ford, Harrison
, Star Wars sci-fi Ford, Harrison
]
War es hilfreich?

Lösung

Printing

It is using the toString() method to print each DVDInfo object.

The println method will do a String.valueOf() on its parameter. Then the println code will print the resulting string.

The parameter you pass println is a List and it has a toString() method of its owh that inserts square braces and commas and calls toString() on the elements, putting the result in between. This produces a string starting with a [ and ending with a ]. Inside those braces are the results of calling the toString() method on the DVDInfo objects and the commas.

That's how it prints.

Sorting

The collections sort() method knows how to traverse the collection and compare the elements to put them into order. It uses standard sorting algorithms to do so. But you don't need to know the algorithm, just that it does the sort. This is the essence of encapsulation. Classes should do one thing and let other classes do their one thing and everything works better.

Inside the sort algorithm, it calls compareTo and then does if statements to either reorder two elements so the the lower one is first or leave the two elements so the lower one is first. It depends on whether they were in order before the sort. Equal can go either way--move or don't. But the sort algorithm gets to decide.

Notes

You might find it interesting to download the source for the Oracle java libraries and connect your IDE to the source so you can click (or whatever) and view the source for the various standard library functions like println and sort. Its sometimes too tedious but sometimes very interesting.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top