ArrayList练习-存储随机数和存储自定义对象
ArrayList练习-存储随机数
生成6个1~33之间的随机整数,添加到集合,并遍历集合。
思路:
1.需要存储6个数字,创建一个集合,<Integer>
2. 产生随机数,需要用到Random
3.用循环6次,来产生6个随机数字:for循环
4.循环内调用r.nextInt(int n),参数是33,0~32,整体+1才是1~33
5.把数字添加到集合中:add
6.遍历集合:for、size、 get
ArrayList<Integer> list2 = new ArrayList<Integer>(); Random r = new Random() ; for (int i = 0; i < 6; i++) { int num1 = r.nextInt( 33) + 1; list2.add(num1) ; } //遍历集合 for (int i = 0; i < list.size(); i++) { System.out.println( list.get(i)); }
ArrayList练习-存储自定义对象
题目:
自定义4个学生对象,添加到集合,并遍历。
思路;
1.自定义Student学生类,四个部分。
2.创建—个集合,用来存储学生对象。泛型:<Student>
3.根据类,创建4个学生对象。
4.将4个学生对象添加到集合中: add5.遍历集合:for、 size、get
public static void main(String[] args) { ArrayList<Student> list = new ArrayList<Student>(); Student one = new Student( "洪七公", 20); Student two = new Student( "欧阳锋", 21); Student three = new Student( "黄药师", 22); Student four = new Student( "段智兴", 23); 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()); }

浙公网安备 33010602011771号