集合框架-ArrayList儲存字串、自定義物件並遍歷泛型版

ZHOU_VIP發表於2017-04-23

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;
	}

}


相關文章