ArrayList
オブジェクトを格納するプログラムを作成していPerson
ます (入力はテキスト ファイルから)。
これは、オブジェクト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());
}
そして、私はComparable
インターフェースを作成しました:
public interface Comparable<T> {
public int compareTo(T o);
}
そして、オブジェクトを格納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);
}
}
ただし、このエラーが発生します。並べ替えは機能しません。
スレッド「メイン」の例外 java.lang.Error: 未解決のコンパイルの問題: バウンドの不一致: Collections 型のジェネリック メソッド sort(List) は、引数 (ArrayList) には適用できません。推論された型 Person は、境界付きパラメーターの有効な代替ではありません >
誰かが理由を知っていますか?私は解決策を求めてグーグルで猛烈に探し回っていますが、何が欠けているのかわかりません。私は同等のものを実装しました..