最近工作中,需要写一些基础的代码,然后发现自己的基础很差,代码质量堪忧,就在B站复习了一下Java基础,遇到好的基础知识点,我就把它记录下来,作为复习笔记;
对象数组的使用、及冒泡法使用示例
package com.winson.array;
/**
* @description: 对象数组练习
* @date: 2020/6/25 18:00
* @author: winson
*/
public class ObjectArray {
public static void main(String[] args) {
//对象数组
Student[] stu = new Student[20];
for (int i = 0; i < stu.length; i++) {
stu[i] = new Student();
stu[i].number = i + 1;
//班级[1, 6]
stu[i].state = (int) (Math.random() * (6 - 1 + 1));
//成绩[0, 100]
stu[i].score = (int) (Math.random() * (100 - 0 + 1));
}
for (Student student : stu) {
System.out.println(student.toString());
}
/*使用冒泡法,按照学生分数升序排序*/
System.err.println("--------------使用冒泡法,按照学生分数升序排序--------------");
for (int i = 0; i < stu.length; i++) {
for (int j = 0; j < stu.length - 1 - i; j++) {
if (stu[j].score > stu[j + 1].score) {
//如果需要换序,交换的是数组的元素:Student对象
Student temp = stu[j];
stu[j] = stu[j + 1];
stu[j + 1] = temp;
}
}
}
for (Student student : stu) {
System.out.println(student.toString());
}
}
}
class Student {
Integer number;
Integer state;
Integer score;
@Override
public String toString() {
return "{"number" :" + number + ", "state" : " + state + ", "score" : " + score + "}";
}
}
关于对象的toString()方法是否重写的作用
如果我们没有将对象的toString()进行重写,那么控制台输出时,结果为对象在堆中的地址值,如下:
System.out.println(student);
结果
com.winson.array.Student@330bedb4
com.winson.array.Student@2503dbd3
com.winson.array.Student@4b67cf4d
com.winson.array.Student@7ea987ac
com.winson.array.Student@12a3a380
com.winson.array.Student@29453f44
com.winson.array.Student@5cad8086
com.winson.array.Student@6e0be858
而如果我们再对象中重写其toString()方法,则结果为:
{"number" :1, "state" : 5, "score" : 97}
{"number" :2, "state" : 4, "score" : 45}
{"number" :3, "state" : 1, "score" : 19}
{"number" :4, "state" : 2, "score" : 98}
{"number" :5, "state" : 2, "score" : 7}
{"number" :6, "state" : 2, "score" : 3}
{"number" :7, "state" : 1, "score" : 27}