day07-常用类-ArrayList-练习
This commit is contained in:
@@ -1,11 +1,27 @@
|
||||
package com.inmind.arraylist03;
|
||||
|
||||
import java.util.ArrayList;
|
||||
|
||||
/*
|
||||
常用类-ArrayList-练习2_添加对象
|
||||
*/
|
||||
public class Demo12 {
|
||||
public static void main(String[] args) {
|
||||
//创建一个保存学生对象的集合
|
||||
ArrayList<Student> students = new ArrayList<>();
|
||||
//往集合中保存3个学生对象
|
||||
Student s1 = new Student(1, 20, "刘备");
|
||||
Student s2 = new Student(2, 21, "关羽");
|
||||
Student s3 = new Student(3, 22, "张飞");
|
||||
|
||||
students.add(s1);
|
||||
students.add(s2);
|
||||
students.add(s3);
|
||||
|
||||
//对集合进行遍历打印学生的学号,年龄和姓名(直接获取属性打印,也可以封装为方法调用)
|
||||
for (int i = 0; i < students.size(); i++) {
|
||||
Student s = students.get(i);
|
||||
s.show();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
41
day07/src/com/inmind/arraylist03/Demo13.java
Normal file
41
day07/src/com/inmind/arraylist03/Demo13.java
Normal file
@@ -0,0 +1,41 @@
|
||||
package com.inmind.arraylist03;
|
||||
|
||||
import java.util.ArrayList;
|
||||
|
||||
/*
|
||||
14.常用类-ArrayList-练习3_指定格式拼接字符串
|
||||
定义以指定格式打印集合的方法(ArrayList类型作为参数),使用@分隔每个元素。并返回
|
||||
格式参照 [元素@元素@元素]。
|
||||
*/
|
||||
public class Demo13 {
|
||||
public static void main(String[] args) {
|
||||
//2.在主方法中调用该方法,获取内容,打印输出
|
||||
ArrayList<String> list = new ArrayList<>();
|
||||
list.add("张三");
|
||||
list.add("李四");
|
||||
list.add("关羽");
|
||||
list.add("刘备");
|
||||
list.add("王五");
|
||||
String result = printList(list);
|
||||
System.out.println(result);
|
||||
|
||||
}
|
||||
|
||||
//1.定义一个方法,作用将对应的集合的内容,获取出来,拼接成[元素@元素@元素],返回
|
||||
public static String printList(ArrayList<String> list){
|
||||
String result = "[";
|
||||
|
||||
for (int i = 0; i < list.size(); i++) {
|
||||
String temp = list.get(i);
|
||||
//如果是最后一个拼接]否则是@
|
||||
if (i == list.size() - 1) {
|
||||
result += temp + "]";
|
||||
} else {
|
||||
result += temp + "@";
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
}
|
||||
9
day07/src/com/inmind/arraylist03/Demo14.java
Normal file
9
day07/src/com/inmind/arraylist03/Demo14.java
Normal file
@@ -0,0 +1,9 @@
|
||||
package com.inmind.arraylist03;
|
||||
/*
|
||||
常用类-ArrayList-练习4_获取偶数集合
|
||||
实现方式2种:
|
||||
1.创建新的集合只保存偶数
|
||||
2.不创建新的集合,只把原集合中不为偶数的数据删除掉即可
|
||||
*/
|
||||
public class Demo14 {
|
||||
}
|
||||
@@ -47,4 +47,9 @@ public class Student {
|
||||
public void study(String book) {
|
||||
System.out.println("在学习");
|
||||
}
|
||||
|
||||
public void show(){
|
||||
String showStr = "学号为"+this.getId()+",年龄为"+age+",姓名为"+this.name;
|
||||
System.out.println(showStr);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user