数组对象排序

来源:互联网 发布:js计算价格的误差 编辑:程序博客网 时间:2024/05/16 16:08

经典学生类:

Java代码:

package cho2;public class TestStudentArray {public static void main(String[] args) {StudentArray sArr = new StudentArray();Student st1 = new Student(100, "d张三", "男", 20);Student st2 = new Student(101, "c李四", "男", 21);Student st3 = new Student(102, "a王五", "女", 22);Student st4 = new Student(103, "b赵六", "男", 23);sArr.insert(st1);sArr.insert(st2);sArr.insert(st3);sArr.insert(st4);sArr.display();System.out.println("------------");sArr.sortByName();sArr.display();System.out.println("------------");sArr.sortByNo();sArr.display();}}
package cho2;public class StudentArray {// 数组private Student[] arr;// 数组中有效数据的大小private int elmes;// 默认构造函数public StudentArray() {arr = new Student[50];}public StudentArray(int max) {arr = new Student[max];}// 插入数据public void insert(Student stu) {arr[elmes] = stu;elmes++;}public void display() {for (int i = 0; i < elmes; i++) {arr[i].display();}}// 按姓名进行排序public void sortByName() {int min = 0;Student temp = null;for (int i = 0; i < elmes - 1; i++) {min = i;for (int j = i + 1; j < elmes; j++) {if (arr[j].getName().compareTo(arr[min].getName()) < 0) {min = j;}}temp = arr[i];arr[i] = arr[min];arr[min] = temp;}}// 按学号进行排序public void sortByNo() {int min = 0;Student temp = null;for (int i = 0; i < elmes - 1; i++) {min = i;for (int j = i + 1; j < elmes; j++) {if (arr[j].getStuNo() < arr[min].getStuNo()) {min = j;}}temp = arr[i];arr[i] = arr[min];arr[min] = temp;}}}

package cho2;public class Student {// 学号private int stuNo;// 姓名private String name;// 性别private String sex;// 年龄private int age;public Student(int stuNo, String name, String sex, int age) {super();this.stuNo = stuNo;this.name = name;this.sex = sex;this.age = age;}public int getStuNo() {return stuNo;}public void setStuNo(int stuNo) {this.stuNo = stuNo;}public String getName() {return name;}public void setName(String name) {this.name = name;}public String getSex() {return sex;}public void setSex(String sex) {this.sex = sex;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}public void display() {System.out.println("学号:" + stuNo + "  姓名:" + name + "  性别:" + sex + "  年龄:" + age);}}



0 0