gpt4 book ai didi

java - 稳定排序java按字母顺序排列数组

转载 作者:行者123 更新时间:2023-12-02 04:21:59 26 4
gpt4 key购买 nike

我第一次尝试运行稳定排序。我创建了一个包含学生对象的数组。现在我想按照名称的字母顺序对该数组中的这些对象进行排序。我不明白的是 Arrays.sort(student,new Students());如果有的话,它的论点应该是什么。非常感谢!

import java.util.Comparator;
import java.util.Arrays;

public class Students implements Comparable<Students> {
private String FirstName;
private String lastName;
private int age;


public Students(String firstName, String lastName, int age) {
super();
FirstName = firstName;
this.lastName = lastName;
this.age = age;
}


public String getFirstName() {
return FirstName;
}


public void setFirstName(String firstName) {
FirstName = firstName;
}


public String getLastName() {
return lastName;
}


public void setLastName(String lastName) {
this.lastName = lastName;
}


public int getAge() {
return age;
}


public void setAge(int age) {
this.age = age;
}
@Override
public int compareTo(Students toCheck) {
int compareQuantity = ((Students)toCheck).getAge();

return this.age-compareQuantity;
}



public static void main(String args[]){
//array for the 6 students
Students[] student= new Students[6] ;
//creating and adding one by one
Students sam = new Students("Sam","Wo", 22 );
student[0]=sam;
Students ben = new Students("Ben","Wang", 27 );
student[1]=ben;
Students arsalan = new Students("Arsalan","Khan", 28);
student[2]=arsalan;
Students issa = new Students("Issa","Hashim", 25 );
student[3]=issa;
//ben khan will test if the last name is different. Should be fun .
Students benK = new Students("Ben","Khan", 29 );
student[4]=benK;
Students jackM = new Students("Jack","Meth", 23);
student[5]=jackM;

Comparator <Students> studentCompare = new Comparator<Students>(){

public int compare (Students s1 , Students s2){
String studentName1 = s1.getFirstName();
String studentName2 = s2.getFirstName();
return studentName1.compareTo(studentName2);

Arrays.sort(student,new Students());

}

}; 为(int i = 0;我

最佳答案

您的 main() 中不需要比较器,因此您可以如下更改 main() 以使其正常工作:

    public static void main(String args[]) {
//array for the 6 students
Students[] student = new Students[6];
//creating and adding one by one
Students sam = new Students("Sam", "Wo", 22);
student[0] = sam;
Students ben = new Students("Ben", "Wang", 27);
student[1] = ben;
Students arsalan = new Students("Arsalan", "Khan", 28);
student[2] = arsalan;
Students issa = new Students("Issa", "Hashim", 25);
student[3] = issa;
//ben khan will test if the last name is different. Should be fun .
Students benK = new Students("Ben", "Khan", 29);
student[4] = benK;
Students jackM = new Students("Jack", "Meth", 23);
student[5] = jackM;

Arrays.sort(student);

}

关于java - 稳定排序java按字母顺序排列数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32673651/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com