|
|
@@ -0,0 +1,94 @@
|
|
|
+package _02_复杂对象练习;
|
|
|
+
|
|
|
+public class StudentTest {
|
|
|
+ public static void main(String[] args) {
|
|
|
+ //1 创建出来一个学生数组
|
|
|
+ Student[] students = new Student[3];
|
|
|
+ //2 可能是2 肯呢个是1 可能3个
|
|
|
+ students[0] = new Student(01L,"zhangsan",18);
|
|
|
+ students[1] = new Student(02L,"lisi",18);
|
|
|
+ students[2] = new Student(03L,"zhaoliu",18);
|
|
|
+ // 要添加学生
|
|
|
+ Student student = new Student(04L,"wangwu",20);
|
|
|
+ // 把student 添加到数组中
|
|
|
+ // 在添加之前需要判断这个添加学生学号是否在数组当中已经存在
|
|
|
+ // 如果不存在就可以添加, 如果存在提醒学号已经是存在了
|
|
|
+ boolean flag = contains(student.getId(),students);
|
|
|
+ if(flag){
|
|
|
+ System.out.println("添加学号已经存在了");
|
|
|
+ }else{
|
|
|
+ System.out.println("添加学号不存在可以正常添加");
|
|
|
+ // 判断数组是否有存满
|
|
|
+ /**
|
|
|
+ * 问题:如何判断数组有没有存满
|
|
|
+ * 如果数组当中不为空的数量 和数组长度相同的说明 数组已经存满了
|
|
|
+ * 如果数组党总不为空的数量小于数组的长度说明没有满
|
|
|
+ */
|
|
|
+ int count = getElementNotNullInArrayCount(students);
|
|
|
+ if(count == students.length){
|
|
|
+ System.out.println("数组已经满了");
|
|
|
+ // 创建一个新的数组, 新的数组长度是之前数组长度+1
|
|
|
+ Student[] newStus = new Student[students.length+1];
|
|
|
+ // 把之前数组内容放到新的数组中
|
|
|
+ for (int i = 0; i < students.length; i++) {
|
|
|
+ // newStus[0] = students[0]
|
|
|
+ // newStus[1]= students[1]
|
|
|
+ // newStus[2] = students[2]
|
|
|
+ // newStus[3] = students[3]
|
|
|
+ newStus[i] = students[i];
|
|
|
+ }
|
|
|
+ // 把添加的元素放到数组当中最后一个位置
|
|
|
+ newStus[newStus.length-1] = student;
|
|
|
+ // 打印数组
|
|
|
+ printArr(newStus);
|
|
|
+ }else{
|
|
|
+ System.out.println("数组还没有满");
|
|
|
+ // 直接把要添加元素放到count索引位置就可以了
|
|
|
+ students[count] = student;
|
|
|
+ // 打印数组当中元素内容
|
|
|
+ printArr(students);
|
|
|
+ }
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ /**
|
|
|
+ * 打印数组
|
|
|
+ * @param students
|
|
|
+ */
|
|
|
+ private static void printArr(Student[] students) {
|
|
|
+ for (Student student : students) {
|
|
|
+ System.out.println(student);
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ private static int getElementNotNullInArrayCount(Student[] students) {
|
|
|
+ // 不为空数量为0
|
|
|
+ int count = 0;
|
|
|
+ for (Student student : students) {
|
|
|
+ if(student!=null){
|
|
|
+ count++;
|
|
|
+ }
|
|
|
+ }
|
|
|
+ return count;
|
|
|
+ }
|
|
|
+ /**
|
|
|
+ * 判断传入学号是否在数组当中已经存在了
|
|
|
+ * 返回值true 表示学号已经在数组当中存在了
|
|
|
+ * 返回值false 表示学号是在数组当中不存在
|
|
|
+ */
|
|
|
+ private static boolean contains(Long id, Student[] students) {
|
|
|
+ /**
|
|
|
+ * NullPointerException : 空指针异常
|
|
|
+ * 原因: 使用null 去调用了属性或者是方法
|
|
|
+ */
|
|
|
+ for (Student student : students) {
|
|
|
+ // 判断当前student 不为哦那个做id 比较, 因为数组当中如果没存满,可能为空null
|
|
|
+ if(student!=null){
|
|
|
+ if(student.getId() == id){
|
|
|
+ return true;
|
|
|
+ }
|
|
|
+ }
|
|
|
+ }
|
|
|
+ return false;
|
|
|
+ }
|
|
|
+}
|