码迷,mamicode.com
首页 > 其他好文 > 详细

集合框架(ArrayList存储自定义对象并遍历泛型版)

时间:2016-04-30 01:17:21      阅读:732      评论:0      收藏:0      [点我收藏+]

标签:集合框架(arraylist存储自定义对象并遍历泛型版)

//集合框架(ArrayList存储自定义对象并遍历泛型版)

package cn.itcast_02;


import java.util.ArrayList;

import java.util.Iterator;


/*

 * 需求:存储自定义对象并遍历。

 * 

 * A:创建学生类

 * B:创建集合对象

 * C:创建元素对象

 * D:把元素添加到集合

 * E:遍历集合

 */

public class ArrayListDemo2 {

public static void main(String[] args) {

// 创建集合对象

// JDK7的新特性泛型推断

// ArrayList<Student> array = new ArrayList<>();

// 但是我不建议这样使用

ArrayList<Student> array = new ArrayList<Student>();


// 创建元素对象

Student s1 = new Student("曹操", 40); // 后知后觉

Student s2 = new Student("蒋干", 30); // 不知不觉

Student s3 = new Student("诸葛亮", 26);// 先知先觉


// 添加元素

array.add(s1);

array.add(s2);

array.add(s3);


// 遍历

Iterator<Student> it = array.iterator();

while (it.hasNext()) {

Student s = it.next();

System.out.println(s.getName() + "---" + s.getAge());

}

System.out.println("------------------");


for (int x = 0; x < array.size(); x++) {

Student s = array.get(x);

System.out.println(s.getName() + "---" + s.getAge());

}

}

}




学生类


package cn.itcast_02;


/**

 * 这是学生描述类

 * 

 * @author 风清扬

 * @version V1.0

 */

public class Student {

// 姓名

private String name;

// 年龄

private int age;


public Student() {

super();

}


public Student(String name, int age) {

super();

this.name = name;

this.age = age;

}


public String getName() {

return name;

}


public void setName(String name) {

this.name = name;

}


public int getAge() {

return age;

}


public void setAge(int age) {

this.age = age;

}


}


本文出自 “GD” 博客,转载请与作者联系!

集合框架(ArrayList存储自定义对象并遍历泛型版)

标签:集合框架(arraylist存储自定义对象并遍历泛型版)

原文地址:http://wangdenghui.blog.51cto.com/9930072/1769060

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