我想知道如何按照从最年轻到最老的整数/年龄顺序对链表addressBook进行排序。我知道Collections.sort(addressBook);会按字母顺序组织列表,但我并不打算在我的最终产品中真正需要它。
import java.io.*;
import java.util.*;
public class ABook
{
public static void main (String args[])
{
LinkedList addressBook = new LinkedList();
Scanner input = new Scanner(System.in);
int n = 0;
do{
System.out.println("Would you like to add a friend? (Say Y or N)");
String reply = input.nextLine();
if(reply.equals("Y"))
{
System.out.println("What is the name of your friend?");
String name = input.nextLine();
System.out.println("What is the age of your friend?");
int age = input.nextInt();
Friend newFriend = new Friend(name,age);
addressBook.add("Name: " + newFriend.name + "; " + "Age: " + newFriend.age);
Collections.sort(addressBook);
System.out.println("This is your Address Book so far: " + addressBook);
n++;
}
...
}
如果有人能让我知道,那就太好了。
谢谢!
发布于 2015-04-15 05:24:02
使用比较器。
import java.io.*;
import java.util.*;
public class ABook
{
public static void main (String args[])
{
LinkedList addressBook = new LinkedList();
Scanner input = new Scanner(System.in);
int n = 0;
do{
System.out.println("Would you like to add a friend? (Say Y or N)");
String reply = input.nextLine();
if(reply.equals("Y"))
{
System.out.println("What is the name of your friend?");
String name = input.nextLine();
System.out.println("What is the age of your friend?");
int age = input.nextInt();
Friend newFriend = new Friend(name,age);
addressBook.add("Name: " + newFriend.name + "; " + "Age: " + newFriend.age);
Comparator<CustomObject> comparator = new Comparator<CustomObject>() {
public int compare(CustomObject c1, CustomObject c2) {
return c2.getAge() - c1.getAge(); // use your logic
}
Collections.sort(addressBook,comparator);
System.out.println("This is your Address Book so far: " + addressBook);
n++;
}
...
}
https://stackoverflow.com/questions/29637524
复制相似问题