gpt4 book ai didi

Java 对对象的数组列表进行排序

转载 作者:行者123 更新时间:2023-11-29 10:16:56 27 4
gpt4 key购买 nike

我正在尝试按照 Sort an arraylist of objects in java 的建议在我的程序中实现排序方法但无法正常工作。我收到错误“找不到符号 - 方法 sort()”

Appologies 是 java 的新手..

入门级:

/**
* The Entry class represents a persons address entry into the system.
* It holds the persons name and address information
*
*/
public class Entry
{
// the person's full name
private String name;
// the steet namd or number
private String street;
// the town
private String town;
// postcode
private String postcode;

/**
* Create a new entry with a given name and address details.
*/
public Entry(String strName, String strStreet, String strTown, String strPostcode)
{
name = strName;
street = strStreet;
town = strTown;
postcode = strPostcode;
}

/**
* Return the address for this person. The address shows the
* street, town and postcode for the person
* @return address
*/
public String getAddress()
{
return name + ", " + street + ", " + town + ", " + postcode;
}

}

地址簿类:

import java.util.*;

/**
* The AddressBook class represents an address book holding multiple persons details. It stores
* the name, street, town, postcode and number of entries.
*/
public class AddressBook
{
private ArrayList < Entry > entries;

/**
* Create a an AddressBook with no limit on the number of entries
*/
public AddressBook()
{
entries = new ArrayList < Entry >();
}

/**
* Return the number of address book entries
* @return the entry amount
*/
public String getAddressBook()
{
String listEntries = "Address Book\n";

listEntries = listEntries + "\nNumber of entries: " + numberOfEntries() +"\n";

entries.sort();

for (int i = 0; i < entries.size(); i++) {
System.out.println(entries.get(i));
}
return listEntries;
}

AddressBookTextUI 类:

import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
* Provides a text based user interface for the AddressBook project.
*
*/
public class AddressBookTextUI {
private AddressBook addressBook;
Scanner myScanner;

/**
* Constructor for objects of class TextUI
*/
public AddressBookTextUI()
{
addressBook = new AddressBook();
myScanner = new Scanner(System.in);

}



private void fullCommand()
{
System.out.println(addressBook.getAddressBook());
clearScreen();
}

}

最佳答案

假设您指的是这个:entries.sort(); ,您需要调用 Collections.sort(List<T> list) Collection.sort(List<T> list, Comparator<T> comparator) .

两者之间的区别在于第一个使用默认行为,可以通过实现 compareTo 在您将要排序的对象中指定该行为。 Comparable 指定的方法接口(interface),而第二个允许您传递比较器对象。这将允许您对相同的列表进行不同的排序。

关于Java 对对象的数组列表进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15153177/

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