如何使用Collection.sort()对集合进行排序

ten*_*kii 1 java

我写的是一个存储程序ArrayListPerson对象(输入是从一个文本文件).

这是Person该类的代码,我将从中创建Person对象:

import java.io.Serializable;

public class Person implements Comparable<Person>, Serializable
{
private String firstName;
private String lastName;
private int age;

public Person(String firstName, String lastName, int age)
{
    this.firstName = firstName;
    this.lastName = lastName.toUpperCase();
    this.age = age;
}

public int getAge() 
{
    return age;
}

public String getName()
{
    return firstName;
}

/**
 * @return a String of the details of a person in the format:
 *      Name: <firstName> <lastName> Age: <age>
 */
public String toString()
{       
    return

            "Name: " + firstName + "" + lastName + "\t\t" + "Age: " + age;
}

/**
 * Compare the age of the current instance of Person to another age of the specified Person
 * @return negative number this < p
 * @return 0 if this == p
 * @return positive number if this > p
 */
public int compareTo(Person p) {
          return ((Integer)this.getAge()).compareTo(p.getAge());
}
Run Code Online (Sandbox Code Playgroud)

我创建了一个Comparable界面:

public interface Comparable<T> {
public int compareTo(T o);
}
Run Code Online (Sandbox Code Playgroud)

这里是被调用类的代码Collection,它将创建一个ArrayList存储Person对象的代码,我省略了代码中不相关的部分,因为它很长:

import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.StringTokenizer;
import java.util.Iterator;

public class Collection
{
private ArrayList<Person> people;

public Collection()
{
    people = new ArrayList<Person>();
}   

public void readFromFile(String filename)
{
    // code that will get input to assign values to fields to a Person

    Person newPerson = new Person(firstNameToken, lastNameToken, ageToken);
}

/**
 * Prints the details of each person held in the people ArrayList
 */
public void printDetails()
{       
    Iterator<Person> it = people.iterator();

        while(it.hasNext())
        {
        Person p = it.next();
        System.out.println(p.toString());
        }
}

public static void main(String [] args) throws FileNotFoundException
{
    Collection c = new Collection(); 

    // check
    //for(Person person : c.people) 
    //{
    //  System.out.println(person);
    //}

    Collections.sort(c.people);
}
}
Run Code Online (Sandbox Code Playgroud)

但是我收到此错误,排序不起作用:

线程"main"中的异常java.lang.Error:未解决的编译问题:绑定不匹配:类型集合的泛型方法sort(List)不适用于参数(ArrayList).推断类型Person不是有界参数>的有效替代

有谁知道为什么?我正在疯狂地寻找谷歌的解决方案,我看不出我错过了什么.我已经实现了类似的..

Bhe*_*ung 6

我创建了一个Comparable接口:public interface Comparable {public int compareTo(T o); }

您不应该创建自己的界面.使用java.lang.Comparable<T>,Collections.sort()方法期望您的对象实现的那个