java - SelectionSort 方法将按类型对 ArrayList 进行排序

标签 java sorting arraylist selection-sort

SOF。我有一个问题,我遇到了一些困难。

下面的代码应该逐行筛选文件,有效地利用 StringTokenizer 来获取汽车类的品牌、型号、年份和里程(按顺序)并将它们存储在汽车对象中,该对象然后我添加到 2 个 ArrayList,其中一个通过 Make“排序”,另一个“未排序”。

我编写的选择排序最初适用于字符串,但由于明显的原因而不起作用。

可以通过使选择排序与对象(汽车)一起使用来解决这个问题吗? Eclipse 向我推荐了这一点,当前的选择排序就是它的产物。

public void readFile(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

        int tokenCount = new StringTokenizer(line, ",").countTokens(); //counts the tokens 
        while (tokenizer.hasMoreTokens()){
            if(tokenCount > 4) {
               System.out.println(" Not 4 tokens");
            }
            else {
               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();
    }
    arraylist2.addAll(arraylist);
    selectionSort(arraylist2);
}

public static void selectionSort(ArrayList<Car> arraylist) //Selection sort using strings
{
  for (int i = 0; i <= arraylist.size(); i++)
  {
    // Look through the unsorted strings (those at j or higher) for the one that is first in order
    int min = i;
    for (arraylist[i].getMake.compareTo(arraylist[min].getMake) < 0) { //use the inherent string compareTo
          min = k;  
    }
    String temp = arraylist[i].getMake; //swapping
    arraylist[i].getMake = arraylist[min].getMake;
    arraylist[min] = temp;
  }
}

任何帮助将不胜感激。

最佳答案

您的新代码不起作用的原因是您只交换了汽车的品牌,而不是完整的 Car 对象。

应该是:

Car temp = arraylist[i]; //swapping
arraylist[i] = arraylist[min];
arraylist[min] = temp;

关于java - SelectionSort 方法将按类型对 ArrayList 进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55192477/

相关文章:

Java:在没有正则表达式的情况下从字符串中删除非字母字符

java - ArrayList 计数相等的对象

java - 我的字典应该使用什么数据结构?

Java 文件 channel 异常

java - Scala 相当于 JavaScript 数组扩展

javascript - 使用 JQuery 按属性对 DIV 进行排序

java - Java ArrayList.clear() 方法的行为是否一致?

java - ArrayList和连接不同的类

java - 从树上的特定类到对象并获取它们的方法(无需多次编写它们)

Java 用不重复的记录填充数组