selectionSort方法,将按类型对ArrayList进行排序

时间:2019-03-16 01:01:23

标签: java sorting arraylist selection-sort

SOF。我有一个遇到困难的问题。

下面的代码应该逐行筛选文件,有效地利用StringTokenizer来获取Car Class的Make,Model,Year和Mileage(按该顺序)并将它们存储在car对象中,然后,我将添加到2个ArrayList中,其中一个是Make进行的“排序”,另一个是“未排序的”。

我最初编写的selectionSort最初使用Strings,但由于明显的原因而无法使用。

可以通过使selectionSort与对象(汽车)一起使用来解决此问题吗? Eclipse向我推荐了该方法,当前的selectionSort是该方法的产物。

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;
  }
}

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:2)

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

应该是:

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