在我使用的代碼下面工作得很好,並輸出除排序方法無效的名稱外。我期望「Collections.sort(nameFromText);」按名稱的字母順序排列ArrayList。使用Java集合對PersonList的ArrayList進行排序
我在做什麼錯?
public static void main(String[] args) throws IOException {
// Create and populate text file
Writer textFile = new FileWriter("names.txt");
String[] nameArray = new String[] { "Tina Tully\n", "Bill Simpson\n",
"Dana Smith\n", "Ralph Andrews\n", "Greg Smithers\n",
"Lisa Krump\n", "Gill Bitters\n", "Barbara West\n",
"Sandra McDonald\n", "Bart Willis\n", "Bucky Zimmerman\n",
"Richard Vicks\n", "Velma Tarp\n", "Winslow Tunnell\n",
"Andrew Letterman\n", "Betty Trump\n", "Waldo Smith\n",
"Kyle Ronno\n", "Vivian West\n", "Wendy Tunnell\n" };
generateText(textFile, nameArray);
// Create object of previously created text file
Scanner pullFile = new Scanner(new File("names.txt"));
// Create 20 Person Objects and add to ArrayList data structure with
// name variables assigned to values from text file
ArrayList<Person> nameFromText = new ArrayList<Person>();
fillArrayList(nameFromText, pullFile);
// Sort ArrayList
Collections.sort(nameFromText);
// Print ArrayList
printNamesFromObjects(nameFromText);
}
private static void printNamesFromObjects(ArrayList<Person> namesFromText) {
for (int i = 0; i < 20; i++) {
System.out.println(namesFromText.get(i).name);
}
}
private static void fillArrayList(ArrayList<Person> nameFromText,
Scanner pullFile) {
while (pullFile.hasNext()) {
Person obj = new Person(pullFile.nextLine());
nameFromText.add(obj);
}
}
private static void generateText(Writer textFile, String[] nameArray)
throws IOException {
for (int i = 0; i < 20; i++) {
textFile.write(new String(nameArray[i]));
}
textFile.close();
}
你會發現這個有用的。 http://www.thejavageek.com/2013/06/17/sorting-user-defined-objects-part-1/和http://www.thejavageek.com/2013/06/17/sorting-user-defined -objects-part-2/ –