这是我为 Crackerpacker 设计的第一个类,我为 arraylist 创建了另一个类,然后将所有这些cracker packers 添加到该 arraylist 中,现在我想按 CrackerPackers 包装的盒子数量的降序对 arraylist 进行排序
public class CrackerPacker {
private String name;
private int numberOfBoxes;
public CrackerPacker (String name, int numberOfBoxes){
this.name = name;
this.numberOfBoxes = numberOfBoxes;
}
public int getNumberOfBoxes() {
return numberOfBoxes;
}
public void setNumberOfBoxes(int numberOfBoxes) {
this.numberOfBoxes = numberOfBoxes;
}
public String getName() {
return name;
enter code here
}
@Override
public String toString() {
return "CrackerPacker{" +
"name='" + name + '\'' +
", numberOfBoxes=" + numberOfBoxes +
'}';
}
public double getwage() {
if ( numberOfBoxes < 51 ) {
return numberOfBoxes * 1.15;
}
else {
double wage = (57.5 + ((numberOfBoxes - 50) * 1.25));
return wage;
这是第二个类,我在其中创建了一个数组列表来添加所有的crackerpacker对象。 我想按照 CrackerPackers 包装的盒子数量的降序对这个数组列表进行排序
import java.util.ArrayList;
import java.util.Collections;
public class Common {
public static ArrayList<CrackerPacker> lectures = new ArrayList<>();
int sum = 0;
int boxes = 0;
public int totalWage() {
for (int i = 0; i < lectures.size(); i++) {
sum += lectures.get(i).getwage();
}
return sum;
}
public int totalBoxes() {
for (int i = 0; i < lectures.size(); i++){
boxes += lectures.get(i).getNumberOfBoxes();
}
return boxes;
这是我的主要方法,我想按对象包装的盒子数量的降序对数组列表进行排序,请告诉我如何做到这一点
import java.util.Collections;
public class Main {
public static void main(String[] args) {
CrackerPacker steve = new CrackerPacker("STEVE", 127);
CrackerPacker gary = new CrackerPacker("Gary", 103);
CrackerPacker tony = new CrackerPacker("tony", 473);
CrackerPacker saad = new CrackerPacker("Saad", 129);
CrackerPacker rubiya = new CrackerPacker("rubiya", 117);
Common common = new Common();
Common.lectures.add(steve);
Common.lectures.add(gary);
Common.lectures.add(tony);
Common.lectures.add(saad);
Common.lectures.add(rubiya);
for ( CrackerPacker element : Common.lectures) {
System.out.println(element);
}
System.out.println(common.totalWage());
System.out.println(common.totalBoxes());
我想我已经使用了compareto方法,但我不知道如何实现它
最佳答案
下面将传入的 CrackerPacker
的 numberOfBoxes
与当前对象的 numberOfBoxes
进行比较。这将产生按降序排序的效果。
public class CrackerPacker implements Comparable<CrackerPacker> {
@Override
public int compareTo(CrackerPacker c) {
return Integer.compare(c.numberOfBoxes, this.numberOfBoxes);
}
}
来自 javadoc,
Compares this object with the specified object for order. Returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.
因此,当比较两个 CrackerPacker 对象时,我们反转 Integer 比较检查以实现降序排列。
示例:比较 5 和 10,我们将 10 与 5 进行比较,因此 Integer.compare 返回 1(因为 10 > 5)。但从外部比较来看,我们指出第一个对象比第二个对象大,因此它将出现在第二个对象之后 (..10....5...)。这将按降序对列表进行排序。
关于java - 我如何在java中按包装盒数量的降序对这个自定义数组列表进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59342072/