Java 对象数组
数组的元素可以是基本数据类型,也可以是引用数据类型。当元素是引用类型中的类时,我们称为对象数组。
1、案例
定义类Student,包含三个属性:学号number(int),年级state(int),成绩score(int)。 创建20个学生对象,学号为1到20,年级和成绩都由随机数确定。
问题一:打印出3年级(state值为3)的学生信息。
问题二:使用冒泡排序按学生成绩排序,并遍历所有学生信息
定义学生类
public class Student { int number; //ID int state; //年级 int score; //分数 @Override public String toString() { return "Student{" + "number=" + number + ", state=" + state + ", score=" + score + '}'; } }
封装工具类
public class StudentUtil { /** * 打印指定年级的学生信息 * * @param students 入参学生数组 * @param state 打印指定年级的学生 */ public void printStudentWIthIndex(Student[] students, int state) { for (Student student : students) { if (state == student.state) { System.out.println(student.toString()); } } } /** * 遍历数组 * * @param students */ public void printStudent(Student[] students) { for (Student student : students) { System.out.println(student.toString()); } } /** * 对象数组 冒泡排序 * * @param students 待排序数组 */ public void sort(Student[] students) { for (int i = 0; i < students.length - 1; i++) { for (int j = 0; j < students.length - 1 - i; j++) { if (students[j].score > students[j + 1].score) { swap(students, j, j + 1); } } } } /** * 按照指定顺序进行排序 * * @param students * @param method */ public void sort(Student[] students, String method) { if ("asc".equals(method)) { for (int i = 0; i < students.length - 1; i++) { for (int j = 0; j < students.length - 1 - i; j++) { if (students[j].score > students[j + 1].score) { swap(students, j, j + 1); } } } } else if ("desc".equals(method)) { for (int i = 0; i < students.length - 1; i++) { for (int j = 0; j < students.length - 1 - i; j++) { if (students[j].score < students[j + 1].score) { swap(students, j, j + 1); } } } } else { System.out.println("啥也不是"); } } /** * 数据交换 * * @param students * @param i * @param j */ private void swap(Student[] students, int i, int j) { int temp = students[i].score; students[i].score = students[j].score; students[j].score = temp; } }
进行测试
public static void main(String[] args) { //创建 STudent 数组 Student[] students = new Student[20]; StudentUtil util = new StudentUtil(); //使用循环数组赋值 for (int i = 0; i < students.length; i++) { students[i] = new Student(); students[i].number = i + 1; students[i].state = (int) (Math.random() * 6 + 1); students[i].score = (int) (Math.random() * 100 + 1); } //打印 年级为 3 的学生信息 util.printStudentWIthIndex(students, 3); //使用冒泡排序按学生成绩排序,然后遍历排序后的结果 util.sort(students,"desc"); System.out.println("----------------------------\n\n"); util.printStudent(students); }