Java对对象的arylylist进行排序

时间:2013-03-01 08:07:00

标签: java arraylist

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

我不熟悉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;
}

}

AddressBook类:

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();
}

}

3 个答案:

答案 0 :(得分:4)

假设您指的是:entries.sort();,则需要致电Collections.sort(List<T> list)Collection.sort(List<T> list, Comparator<T> comparator)

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

答案 1 :(得分:3)

您需要使用Collections.sort(List<T> list)

列表是一个界面。 ArrayList间接实现List接口。

答案 2 :(得分:1)

  1. Make Entry实现可比较:

    public class Entry实现Comparable

  2. 添加int compareTo(Entry otherEntry)方法(简化伪代码):

    if this > otherEntry return 1
    else if this < otherEntry return -1
    else return 0
    
  3. 调用Collections.sort(您的条目数组)