【发布时间】:2019-03-16 09:18:38
【问题描述】:
Collections.sort() 是否可以在 Car 对象数组列表中按 Make 进行排序?在那里添加空值后,我没有收到任何错误消息,但我的目标是具体按 Make 对它们进行排序,但我不完全确定如何去做。
public void readingFromFile(String file) throws FileNotFoundException //an object array that takes in string files
{
try {
File myFile = new File(file); //converts the parameter string into a file
Scanner scanner = new Scanner(myFile); //File enables us to use Scanner
String line = scanner.nextLine(); //reads the current line and points to the next one
StringTokenizer tokenizer = new StringTokenizer(line, ","); //tokenizes the line, which is the scanned file
//counts the tokens
while (tokenizer.hasMoreTokens()){
String CarMake = tokenizer.nextToken(); //since car is in order by make, model, year, and mileage
String CarModel = tokenizer.nextToken();
int CarYear1 = Integer.parseInt(tokenizer.nextToken());
int CarMileage1 = Integer.parseInt(tokenizer.nextToken()); //converts the String numbers into integers
Car cars = new Car(CarMake, CarModel, CarYear1, CarMileage1); //since the car has a fixed order
arraylist.add(cars); //add the cars to the unsorted array
}
scanner.close(); //close the scanner
} catch (FileNotFoundException f){
f.printStackTrace();
return;
}
arraylist2.addAll(arraylist);
Collections.sort(arraylist2, null);
}
【问题讨论】:
-
您是否打算阅读不止一行?另外,您为什么要将列表添加到第二个列表中?这段代码没有意义。
-
必须实现一个比较器。 Look at this example
-
导入 java.util.Comparator; public class makeCompare implements Comparator
{ public int compare(Car car1, Car car2) { // 如下写比较逻辑,只是一个示例 return car1.getMake().compareTo(car2.getMake()); } } -
@Yingkai 然后,Collections.sort(arraylist2, new makeCompare());这是否适用于文本文件中包含多行 Make、Model、Year 和 Mileage 的文件?
-
@ElliottFrisch 是的,它是一个完整的行文本文件。不过你说得对,我可以解决这个问题。