数组对象排序

经典学生类:

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
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值