diff --git a/day07/src/com/inmind/arraylist03/Student.java b/day07/src/com/inmind/arraylist03/Student.java new file mode 100644 index 0000000..98c2da7 --- /dev/null +++ b/day07/src/com/inmind/arraylist03/Student.java @@ -0,0 +1,20 @@ +package com.inmind.arraylist03; + +public class Student { + String name; + int age; + String gender; + + public Student() { + } + + public Student(String name, int age, String gender) { + this.name = name; + this.age = age; + this.gender = gender; + } + + public void showSelf(){ + System.out.println("当前学生叫"+this.name+",年龄"+this.age+"岁,性别为"+this.gender); + } +} diff --git a/day07/src/com/inmind/arraylist03/Test12.java b/day07/src/com/inmind/arraylist03/Test12.java new file mode 100644 index 0000000..aa7a1c3 --- /dev/null +++ b/day07/src/com/inmind/arraylist03/Test12.java @@ -0,0 +1,36 @@ +package com.inmind.arraylist03; + +import java.util.ArrayList; + +/* +常用类-ArrayList-练习2_添加对象 +创建一个ArrayList集合,存放3个Student对象,再把他们的学号,姓名,性别输出 + */ +public class Test12 { + public static void main(String[] args) { + //1.创建存放学生的集合 + ArrayList list = new ArrayList<>(); + //2.先创建学生对象,再放入集合 + /*Student s1 = new Student("张三1",19,"男"); + Student s2 = new Student("张三2",18,"女"); + Student s3 = new Student("张三3",20,"男"); + list.add(s1); + list.add(s2); + list.add(s3);*/ + list.add(new Student("张三1",19,"男")); + list.add(new Student("张三2",18,"女")); + list.add(new Student("张三3",20,"男")); + System.out.println(list.size());//3个学生 + //方式一:集合的遍历,把每个对象的属性打印出来 + for (int i = 0; i < list.size(); i++) { + Student s = list.get(i); + System.out.println("当前学生叫"+s.name+",年龄"+s.age+"岁,性别为"+s.gender); + } + System.out.println("-----------------"); + //方式二:直接在Student类中定义展示方法,集合的遍历,调用各个学生对象的展示方法 + for (int i = 0; i < list.size(); i++) { + Student s = list.get(i); + s.showSelf(); + } + } +} diff --git a/day07/src/com/inmind/arraylist03/Test13.java b/day07/src/com/inmind/arraylist03/Test13.java new file mode 100644 index 0000000..5bee810 --- /dev/null +++ b/day07/src/com/inmind/arraylist03/Test13.java @@ -0,0 +1,36 @@ +package com.inmind.arraylist03; + +import java.util.ArrayList; + +//常用类-ArrayList-练习3_指定格式拼接字符串 +public class Test13 { + public static void main(String[] args) { + ArrayList list = new ArrayList(); + list.add("张三"); + list.add("李四"); + list.add("王五"); + list.add("王五"); + list.add("王五"); + list.add("王五"); + list.add("王五"); + printList(list); + } + + //定义以指定格式打印集合的方法(ArrayList类型作为参数),使用@分隔每个元素。格式参照 [元素1@元素2@元素3]。 + public static void printList(ArrayList arrayList) { + String result = "["; + //对集合进行遍历 + for (int i = 0; i < arrayList.size(); i++) { + //获取集合中的元素 + String element = arrayList.get(i); + //如果是最后一个元素(size-1):那就拼接]而不是@ + if (i == (arrayList.size() - 1)) { +// result = result + element + "]"; + result += element + "]"; + } else { + result += element + "@"; + } + } + System.out.println(result); + } +}