首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何对用户定义对象的链表进行排序?

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

Stack Overflow用户
提问于 2015-04-15 05:14:22
回答 2查看 719关注 0票数 0

我想知道如何按照从最年轻到最老的整数/年龄顺序对链表addressBook进行排序。我知道Collections.sort(addressBook);会按字母顺序组织列表,但我并不打算在我的最终产品中真正需要它。

代码语言:javascript
运行
复制
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++;
    }     
      ...
}

如果有人能让我知道,那就太好了。

谢谢!

EN

Stack Overflow用户

发布于 2015-04-15 05:24:02

使用比较器。

代码语言:javascript
运行
复制
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++;
    }     
      ...
}

票数 1
EN
查看全部 2 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/29637524

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档