无法弄清楚为什么对象的ArrayList未能正确排序

huangapple go评论135阅读模式
英文:

Can't figure out why is ArrayList of objects not sorted properly

问题

我正在为一个对象的 ArrayList 编写交换排序,以便根据对象中的值升序排序。当我编译它时,一切都很好,直到最后一个元素没有正确排序。我怀疑问题出在迭代器上。我尝试了许多组合,但它无法正确排序。另外,我不能使用 sort() 或任何预构建的库。我会感激任何指导!

void sortAndDisplay(ArrayList<Car> cars) {
    Car temp;
    
    for (int i = 0; i < cars.size() - 1; i++) {
        for (int j = i + 1; j < cars.size(); j++) {
            if (((cars.get(i).getMake()).compareToIgnoreCase(cars.get(j).getMake()) > 0)) {
                temp = cars.get(i);
                cars.set(i, cars.get(j));
                cars.set(j, temp);
            }
        }
    }
    
    for (int i = 0; i < cars.size(); i++) {
        System.out.print(cars.get(i) + "\n\n");
    }
}

Car 类:

public class Car {
    String make;
    String model;
    
    public Car(String make, String model) {
        this.make = make;
        this.model = model;
    }
    
    public String getMake() {
        return make;
    }
}

从文件中读取值的方法:

ArrayList<Car> readCars(FileReader file) throws Exception {
    String arr[] = {};
    String line = "";
    BufferedReader scan = new BufferedReader(file);
    ArrayList<Car> carsArr = new ArrayList<Car>();
    
    while ((line = scan.readLine()) != null) {
        arr = line.split(",");
        Car car = new Car(arr[0], arr[1]);
        carsArr.add(car);
    }
    System.out.println("The file was read.");
    return carsArr;
}
英文:

I'm working on an exchange sort for an ArrayList of objects so that it can be sorted ascending depending on the value in the object. When I compile it, everything works great until the last element is not sorted properly. I suspect that the problem is with the iterator. I tried many combinations but it won't sort properly. Also, I can't use sort() or any prebuilt libraries. I'd appreciate any guidance!

void sortAndDisplay (ArrayList&lt;Car&gt; cars) {
	
	Car temp;
	
	for (int i = 0; i &lt; cars.size() -1; i++) {
        for (int j = i+1; j &lt; cars.size(); j++ ) {
            if (((cars.get(i).getMake()).compareToIgnoreCase(cars.get(j).getMake()) &gt; 0)) {
                temp = cars.get(i);
                cars.set(i, cars.get(j));
                cars.set(j, temp);
            }


        }
    }
	
	
	  for (int i = 0; i &lt; cars.size(); i++) { 
		  System.out.print(cars.get(i)+&quot;\n\n&quot;);

      }

	
}

The Car class:

public class Car {
String make;
String model;


public Car (String make,
		    String model)   {

	this.make = make;
	this.model = model;
	
}

public String getMake() {
	return make;
	
}

The method I used to read the values from the file:

ArrayList&lt;Car&gt; readCars(FileReader file) throws Exception  {
	String arr[] = {};
	String line = &quot;&quot;;
	BufferedReader scan = new BufferedReader(file);
	ArrayList&lt;Car&gt; carsArr = new ArrayList&lt;Car&gt;();
	
	while ((line = scan.readLine()) != null) {
		arr = line.split(&quot;,&quot;); 
		Car car = new Car(arr[0], arr[1]);
		carsArr.add(car);
	}
	System.out.println(&quot;The file was read.&quot;);
	return carsArr;
	
}

答案1

得分: 1

Sure, here's the translation:

void sortAndDisplay(List<Car> cars) {
    cars.sort(Comparator.comparing(Car::getMake));
    System.out.println(cars.stream().collect(Collectors.joining("\n\n")));
}
英文:

java has sorting built in:

void sortAndDisplay (List&lt;Car&gt; cars) {
    cars.sort(Comparator.comparing(Car::getMake));
    System.out.println(cars.stream().collect(Collectors.joining(&quot;\n\n&quot;)));
}

答案2

得分: 0

我创建了文件 x.txt,其中包含以下数据:

WERTfgd, bmw
ETRHFDdfgsdf, bmw
ewrd, bmw
HTfgdfgs, bmw
dDSFSfgd, bmw
ter, bmw
jhvbn, bmw
Frqw, bmw

我按字面意思复制了您的代码,将 getMake() 添加到了 System.out.print(cars.get(i).getMake() + "\n\n"); 中,以获得所需的输出...

输出

dDSFSfgd

ETRHFDdfgsdf

ewrd

Frqw

HTfgdfgs

jhvbn

ter

WERTfgd

这是正确的输出,所以我无法理解您的问题。

也许您不确定 compareToIgnoreCase() 方法是如何工作的?

英文:

I created the file x.txt with the following data:

WERTfgd, bmw
ETRHFDdfgsdf, bmw
ewrd, bmw
HTfgdfgs, bmw
dDSFSfgd, bmw
ter, bmw
jhvbn, bmw
Frqw, bmw

I copied your code literally by adding getMake() into this System.out.print (cars.get (i) .getMake () + &quot;\ n \ n&quot;); in order to get the wanted output...

Output

dDSFSfgd

ETRHFDdfgsdf

ewrd

Frqw

HTfgdfgs

jhvbn

ter

WERTfgd

Which is correct, so I can't figure out what's your problem.

Maybe you are not sure how the method compareToIgnoreCase() works?

答案3

得分: 0

用短的示例列表尝试了你的代码,它运行正常。你能提供一个失败的示例输入以及相应的输出吗?

顺便说一句,我建议在 Car 类中添加一个 toString() 方法。例如:

@Override
public String toString() {
    return "<Car<" + make + "><" + model + ">>";
}

有了这个方法,可以这样打印汽车列表:

System.out.println(cars);
英文:

Tried your code with short example list and it worked. Could you give a failing example input with corresponding output?

BTW I recommend adding a toString() method to the Car class. For example:

@Override
public String toString() {
    return &quot;&lt;Car&lt;&quot; + make + &quot;&gt;&lt;&quot; + model + &quot;&gt;&gt;&quot;;
}

With that printing the list of cars can be done like:

System.out.println(cars);

huangapple
  • 本文由 发表于 2020年5月5日 04:47:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/61601332.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定