1. 程式人生 > >ArrayList儲存字串並且遍歷——ArrayList儲存自定義物件並且遍歷

ArrayList儲存字串並且遍歷——ArrayList儲存自定義物件並且遍歷

ArrayList儲存字串並且遍歷輸出——ArrayList儲存自定義物件並且遍歷輸出

1、ArrayList儲存字串並遍歷。

        遍歷方式A:    迭代器

        遍歷方式B:    普通for

        遍歷方式C:    增強for

2、程式碼演示

package cn.itcast_01;

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

/*
 * ArrayList儲存字串並遍歷。要求加入泛型,並用增強for遍歷。
 * A:迭代器
 * B:普通for
 * C:增強for
 */
public class ArrayListDemo {
	public static void main(String[] args) {
		// 建立集合物件
		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
		for (int x = 0; x < array.size(); x++) {
			String s = array.get(x);
			System.out.println(s);
		}
		System.out.println("------------------");

		// 增強for
		for (String s : array) {
			System.out.println(s);
		}
	}
}

3、ArrayList儲存自定義物件並且遍歷輸出

        遍歷方式A:    迭代器

        遍歷方式B:    普通for

        遍歷方式C:    增強for

4、程式碼演示

(學生類)

package cn.itcast_01;

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

	// 成員方法
	// getXxx()/setXxx()
	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;
	}
}

****************************************

(測試類)

package cn.itcast_01;

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

/*
 * 需求:ArrayList儲存自定義物件並遍歷。要求加入泛型,並用增強for遍歷。
 * A:迭代器
 * B:普通for
 * C:增強for
 * 
 * LinkedList,Vector,Colleciton,List等儲存我還講嗎?不講解了,但是要求你們練習。
 * 
 * 增強for是用來替迭代器。
 */
public class ArrayListDemo2 {
	public static void main(String[] args) {
		// 建立集合物件
		ArrayList<Student> array = new ArrayList<Student>();

		// 建立學生物件
		Student s1 = new Student("林青霞", 27);
		Student s2 = new Student("貂蟬", 22);
		Student s3 = new Student("楊玉環", 24);
		Student s4 = new Student("西施", 21);
		Student s5 = new Student("王昭君", 23);

		// 把學生物件新增到集合中
		array.add(s1);
		array.add(s2);
		array.add(s3);
		array.add(s4);
		array.add(s5);

		// 迭代器
		Iterator<Student> it = array.iterator();
		while (it.hasNext()) {
			Student s = it.next();
			System.out.println(s.getName() + "---" + s.getAge());
		}
		System.out.println("---------------");

		// 普通for
		for (int x = 0; x < array.size(); x++) {
			Student s = array.get(x);
			System.out.println(s.getName() + "---" + s.getAge());
		}
		System.out.println("---------------");

		// 增強for
		for (Student s : array) {
			System.out.println(s.getName() + "---" + s.getAge());
		}
	}
}