gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 04:46:15 25 4
gpt4 key购买 nike

我想知道如何订购链表 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++;
}
...
}

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

谢谢!

最佳答案

实现比较器然后调用

Collections.sort(addressBook, yourComparator);

关于java - 如何对用户定义对象的链接列表进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29637524/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com