您的位置:首页 > 其它

集合框架-ArrayList存储字符串、自定义对象并遍历泛型版

2017-04-23 12:59 393 查看
package cn.itcast_02;

import java.util.ArrayList;
import java.util.Iterator;

/*
* 泛型在哪些地方使用呢?
* 		看API,如果类,接口,抽象类后面跟的有<E>就说要使用泛型。一般来说就是在集合中使用。
*/
public class ArrayListDemo {
public static void main(String[] args) {
// 用ArrayList存储字符串元素,并遍历。用泛型改进代码
ArrayList<String> array = new ArrayList<String>();

array.add("hello");
array.add("world");
array.add("java");

Iterator<String> it = array.iterator();
while (it.hasNext()) {
String s = it.next();
System.out.println(s);
}
System.out.println("-----------------");

for (int x = 0; x < array.size(); x++) {
String s = array.get(x);
System.out.println(s);
}
}
}
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;
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: