import java.util.ArrayList;publicclassDemo06ArrayListStudent{publicstaticvoidmain(String[] args){
ArrayList<Student> list =newArrayList<>();//创建一个Student类型的集合
Student one =newStudent("学生1",17);//创建四个Student对象
Student two =newStudent("学生2",24);
Student three =newStudent("学生3",21);
Student four =newStudent("学生4",22);
list.add(one);//将四个Student对象添加入集合中
list.add(two);
list.add(three);
list.add(four);for(int i =0; i < list.size(); i++){//遍历集合
System.out.println(list.get(i));//直接输出list.get(i)是每个对象的地址
Student stu = list.get(i);//要输出对象的属性信息,先创建一个Student对象接收每个集合中的元素,再使用Getter方法获取private属性值
System.out.println("姓名:"+ stu.getName()+",年龄:"+ stu.getAge());}}}
9、ArrayList作为方法的参数
//将ArrayList中的元素按{xianxian@Salty@Julie}格式输出import java.util.ArrayList;publicclassDemo07ArrayListParam{publicstaticvoidmain(String[] args){
ArrayList<String> list =newArrayList<>();//创建
list.add("xianxian");//添加元素
list.add("Salty");
list.add("Julie");printArrayList(list);//调用方法 {xianxian@Salty@Julie}}publicstaticvoidprintArrayList(ArrayList<String> list){//AraayList类型作为方法参数
System.out.print("{");//不要换行for(int i =0; i < list.size(); i++){if(i==list.size()-1){//注意size要-1
System.out.print(list.get(i)+"}");}else{
System.out.print(list.get(i)+"@");}}}}
10、ArrayList作为方法的返回值
//随机生成一个ArrayList<Integer>,找出其中为偶数的元素,存为新的集合import java.util.ArrayList;import java.util.Random;publicclassDemo08ArrayListReturn{publicstaticvoidmain(String[] args){
ArrayList<Integer> bigList =newArrayList<>();//创建
ArrayList<Integer> smallList =newArrayList<>();
Random r =newRandom();for(int i =0; i <5; i++){int num = r.nextInt(10)+1;
bigList.add(num);}
System.out.println("bigList:"+ bigList);//bigList:[5, 9, 5, 4, 2]
smallList =getSmallList(bigList);
System.out.println("smallList:"+ smallList);//smallList:[4, 2]}publicstatic ArrayList<Integer>getSmallList(ArrayList<Integer> bigList){//ArrayList<Integer> 作为方法返回值和参数
ArrayList<Integer> smallList =newArrayList<>();//创建for(int i =0; i < bigList.size(); i++){if(bigList.get(i)%2==0){
smallList.add(bigList.get(i));}}return smallList;}}