下面我贴了整个code
。
对于我们读取的 dvdinfo.txt 中的每一行文本,我们正在创建 DVDInfo 类的新实例并将其存储在 ArrayList 中。到目前为止,考虑这个类没有实现任何接口,并且在 main 方法中不使用任何排序方法。因此,在该标准中,当我们打印dvdList
arraylist 时,它会打印文件中的所有内容而不进行排序。我的第一个疑问是存储在 ArrayList 中的新实例如何正确打印文本,我们没有使用任何 getter 方法将文本存储在 ArrayList 中。
现在考虑它在 main 中实现类似接口和 collections.sort() 的整个代码。
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
在下面的代码中,它实现了 compareTo() 方法。如何从 sort 调用此 compareTo() 以及这如何int values
有助于 sort 方法对对象进行排序。当我们仅将标题对象与该对象进行比较时,它是如何工作的,以及排序是如何发生的。collections.sort(dvdlist) 如何与这个 compareTo() 方法一起工作?
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
我的DVD.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");}
}
}
输出:
[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
]