无法弄清楚如何从扩展类中对arrayList进行排序......
继承人我所拥有的:
地址簿类:
import java.util.ArrayList;
import java.util.Iterator;
public class AddressBook
{
private ArrayList<Entry> data;
public AddressBook()
{
this.data = new ArrayList();
}
public String add(Entry paramEntry)
{
//Some code }
public ArrayList<Entry> getAddressBook()
{
return this.data;
}
public String getAll()
{
//Some code
}
}
Run Code Online (Sandbox Code Playgroud)
ExtendedAddressBook类:
import java.util.*;
import java.lang.Comparable;
public class ExtendedAddressBook extends AddressBook
{
public ExtendedAddressBook()
{
}
public String getAll()
{
String listAll = "Address Book\n";
ArrayList<Entry> allEntries = getAddressBook();
Collections.sort(allEntries);
for ( Entry entry : allEntries )
{
ListAll = ListAll + entry.toString();
}
return ListAll;
}
}
Run Code Online (Sandbox Code Playgroud)
AllEntries类:
import java.lang.Comparable;
public class AllEntries extends Entry implements Comparable<Entry>
{
public int compareTo(Entry otherEntry)
{
int d = this.getFirstName().compareTo(otherEntry.getFirstName());
if (d == 0)
{
d = this.getLastName().compareTo(otherEntry.getLastName());
}
return d;
}
}
Run Code Online (Sandbox Code Playgroud)
当我尝试编译时,我在以下行Collections.sort(allEntries)上找到'找不到合适的排序方法(java.util.ArrayList); 在ExtendedAddressBook类中.有人能指出我哪里出错了,如果它甚至可以扩展一个类,那么arrayList可以排序吗?谢谢
你有几个问题.首先,创建一个AllEntries类,扩展Entry添加Comparable接口,但实际上并不创建任何AllEntries对象.但无论如何你不应该这样做.相反,你应该这样做:
Collections.sort(allEntries, new Comparator<Entry>() {
public int compare(Entry o1, Entry o2) {
return o1.getFirstName().compareTo( o2.getFirstName() );
}
});
Run Code Online (Sandbox Code Playgroud)
----完整示例----
package com.example;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Collections;
import java.util.List;
public class SortExample {
private static class Entry {
private String firstName;
private String lastName;
public Entry( String firstName, String lastName ) {
this.firstName = firstName;
this.lastName = lastName;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public String toString() {
return firstName + " " + lastName;
}
}
public static void main( String[] args ) {
List<Entry> list = new ArrayList<Entry>();
list.add( new Entry( "Homer", "Simpson" ) );
list.add( new Entry( "George", "Jettson" ) );
list.add( new Entry( "Fred", "Flinstone" ) );
list.add( new Entry( "Fred", "Durst" ) );
Collections.sort( list, new Comparator<Entry>() {
public int compare( Entry o1, Entry o2 ) {
int compareValue = o1.getFirstName().compareTo( o2.getFirstName() );
if ( compareValue == 0 ) {
compareValue = o1.getLastName().compareTo( o2.getLastName() );
}
return compareValue;
}
} );
for ( Entry entry : list ) {
System.out.println( entry );
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1537 次 |
| 最近记录: |