码迷,mamicode.com
首页 > 编程语言 > 详细

java 16 -11 ArrayList存储自定义对象并增强for遍历

时间:2016-09-22 23:57:20      阅读:229      评论:0      收藏:0      [点我收藏+]

标签:

 

  需求:ArrayList存储自定义对象并遍历。要求加入泛型,并用增强for遍历。
    A:迭代器
    B:普通for
       C:增强for

      LinkedList,Vector,Colleciton,List等存储继续练习

     增强for是用来替迭代器。

 1 package cn_JDK5new;
 2 
 3 import java.util.ArrayList;
 4 import java.util.Iterator;
 5 
 6 
 7 public class ArrListDemo2 {
 8 public static void main(String[] args) {
 9 //创建集合 注意:这里是存储自定义对象,则类型里要填那个对象的类名
10 ArrayList<Person> alt = new ArrayList<Person>();
11 
12 //创建自定义对象
13 Person s1 = new Person("阿猫","女",20);
14 Person s2 = new Person("阿狗","男",22);
15 Person s3 = new Person("张三","男",19);
16 Person s4 = new Person("阿拉尔","女",20);
17 
18 //添加元素到集合
19 alt.add(s1);
20 alt.add(s2);
21 alt.add(s3);
22 alt.add(s4);
23 
24 //遍历
25 //迭代器
26 Iterator<Person> it = alt.iterator();
27 while(it.hasNext()){
28 Person p1 = it.next();
29 System.out.println(p1.getName()+"\t"+p1.getSex()+"\t"+p1.getAge());
30 }
31 System.out.println("------------");
32 
33 //普通for
34 for(int x = 0;x < alt.size(); x++){
35 Person p2= alt.get(x);
36 System.out.println(p2.getName()+"\t"+p2.getSex()+"\t"+p2.getAge());
37 }
38 System.out.println("------------");
39 
40 //增强for
41 for(Person p3 : alt){
42 System.out.println(p3.getName()+"\t"+p3.getSex()+"\t"+p3.getAge());
43 }
44 }
45 }

 

java 16 -11 ArrayList存储自定义对象并增强for遍历

标签:

原文地址:http://www.cnblogs.com/LZL-student/p/5898330.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!