控制台程序。
public class Person implements Comparable<Person> {
// Constructor
public Person(String firstName, String surname) {
this.firstName = firstName;
this.surname = surname;
} @Override
public String toString() {
return firstName + " " + surname;
} // Compare Person objects
public int compareTo(Person person) {
int result = surname.compareTo(person.surname);
return result == 0 ? firstName.compareTo(person.firstName) : result;
} private String firstName; // First name of person
private String surname; // Second name of person
}
使用sort()方法对列表排序时,必须通过某种方式确定列表中对象的顺序。最合适的方式就是在Person类中实现Comparable<>接口。Comparable<>只声明了comparableTo()方法。
如果集合中存储的对象的类型实现了Comparable<>接口,就可以把集合对象作为参数传送给sort()方法。
import java.util.Vector;
import java.util.ListIterator;
import java.util.Collections;
import java.io.*; public class TryVector {
public static void main(String[] args) {
Person aPerson = null; // A person object
Vector<Person> filmCast = new Vector<>(); // Populate the film cast
while(true) { // Indefinite loop
aPerson = readPerson(); // Read in a film star
if(aPerson == null) { // If null obtained...
break; // We are done...
}
filmCast.add(aPerson); // Otherwise, add to the cast
} int count = filmCast.size();
System.out.println("You added " + count + (count == 1 ? " person": " people") + " to the cast:");
// Show who is in the cast using an iterator
ListIterator<Person> thisLot = filmCast.listIterator(); while(thisLot.hasNext()) { // Output all elements
System.out.println( thisLot.next());
}
System.out.println("\nThe vector currently has room for " + (filmCast.capacity() - count) + " more people."); // Now sort the vector contents and list it
Collections.sort(filmCast);
System.out.println("\nThe cast in ascending sequence is:");
for(Person person : filmCast) {
System.out.println(person);
}
} // Read a person from the keyboard
static Person readPerson() {
// Read in the first name and remove blanks front and back
String firstName = null;
String surname = null;
System.out.println("\nEnter first name or ! to end:");
try {
firstName = keyboard.readLine().trim(); // Read and trim a string if(firstName.charAt(0) == '!') { // Check for ! entered
return null; // If so, we are done...
} // Read in the surname, also trimming blanks
System.out.println("Enter surname:");
surname = keyboard.readLine().trim(); // Read and trim a string
} catch(IOException e) {
System.err.println("Error reading a name.");
e.printStackTrace();
System.exit(1);
}
return new Person(firstName,surname);
} static BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in));
}
把filmCast对象传送给Collections类的sort()静态方法,就会导致对集合中的对象排序。
键盘对象是InputStreamReader对象中封装的System.in,而InputStreamReader对象封装在BufferedReader对象中。InputStreamReader对象可以把输入从字节流System.in转换为字符。BufferedReader对象缓存了从InputStreamReader读入的数据。因为输入包含一系列字符串,而每个字符串占一行,所以readLine()方法可以完成我们需要的工作。