packagecn.hei.array;importjava.util.ArrayList;importjava.util.Random;/*
题目:生成6个1~33之间的随机数,添加到集合,并遍历集合。
思路:
1.需要创建6个数字,创建一个集合,<Integer>
2.产生随机数,需要用到Random
3.用循环6次,来产生6个随机数字:for循环
4.循环内调用r.nextInt(int n),参数的33.0~32,需要整体加1
5.把数字添加到集合中:add
遍历集合:for、size、get
*/publicclassWork01ArrayListRandom{
publicstaticvoidmain(String[] args){
Random r =newRandom();ArrayList<Integer> list =newArrayList<>();for(int i =0; i <6; i++){
int num = r.nextInt(33)+1;
list.add(num);}for(int j =0; j < list.size(); j++){
System.out.println(list.get(j));}}}
packagecn.hei.array;importjava.util.ArrayList;/*
题目:自定义四个学生对象,添加到集合,并遍历
思路:
1.自定义Student学生类,四个部分
2.创建一个集合,用来存储存储学生对象,泛型:<Studeng>
3.根据类,创建四个学生对象
4.将四个学生对象添加到集合中:add
5.遍历集合:for、size、get
*/publicclassWork02ArrayListStudent{
publicstaticvoidmain(String[] args){
ArrayList<Student> list =newArrayList<>();Student one =newStudent("张",12);Student two =newStudent("王",22);Student three =newStudent("李",14);Student four =newStudent("士大夫",16);
list.add(one);
list.add(two);
list.add(three);
list.add(four);//遍历集合for(int i =0; i < list.size(); i++){
Student stu = list.get(i);System.out.println("姓名:"+stu.getName()+"年龄:"+stu.getAge());}}}