如何对用户定义对象的链接列表进行排序?

时间:2015-04-14 21:14:22

标签: java sorting linked-list integer user-defined

我想知道如何按照从最小到最旧的整数/年龄顺序排列链表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++;
    }     
      ...
}




如果有人能告诉我,那就太棒了。

谢谢!

2 个答案:

答案 0 :(得分:1)

使用比较器。



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++;
    }     
      ...
}
&#13;
&#13;
&#13;

答案 1 :(得分:1)

实现比较器,然后调用

Collections.sort(addressBook, yourComparator);