簡體   English   中英

Java對對象的數組列表進行排序

[英]Java sort an arraylist of objects

我試圖按照對Java中的對象的數組列表進行排序的建議,在程序中實現排序方法但無法正常工作。 我收到錯誤“找不到符號-方法sort()”

應用程序學是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();
}

}

假設您引用的是: entries.sort(); ,則需要調用Collections.sort(List<T> list)Collection.sort(List<T> list, Comparator<T> comparator)

兩者之間的區別在於,第一個使用默認行為,可以通過實現Comparable接口指定的compareTo方法在要排序的對象中指定默認行為,而第二個則允許您傳遞比較器對象。 這將允許您對同一列表進行不同的排序。

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

列表是一個接口。 ArrayList間接實現List接口。

  1. 使Entry工具可比較:

    公共類入門工具可比

  2. 添加int compareTo(Entry otherEntry)方法(簡化的偽代碼):

     if this > otherEntry return 1 else if this < otherEntry return -1 else return 0 
  3. 調用Collections.sort(您的條目數組)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM