集合框架ArrayList存儲(chǔ)字符串并遍歷泛型版;ArrayList存儲(chǔ)自定義對(duì)象并遍歷泛型版

ArrayList存儲(chǔ)字符串并遍歷泛型版

  package com.ithelei;

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

/*
 * 泛型在哪些地方使用呢?
 *      看API,如果類,接口,抽象類后面跟的有<E>就說要使用泛型。一般來說就是在集合中使用。
 */
public class ArrayListDemo {
public static void main(String[] args) {
    // 用ArrayList存儲(chǔ)字符串元素,并遍歷。用泛型改進(jìn)代碼
    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);
        }
    }
}

ArrayList存儲(chǔ)自定義對(duì)象并遍歷泛型版

  package com.ithelei;

/**
 * 這是學(xué)生描述類
 * 
 * @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;
    }

}

//

  package com.ithelei;

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

/*
 * 需求:存儲(chǔ)自定義對(duì)象并遍歷。
 * 
 * A:創(chuàng)建學(xué)生類
 * B:創(chuàng)建集合對(duì)象
 * C:創(chuàng)建元素對(duì)象
 * D:把元素添加到集合
 * E:遍歷集合
 */
public class ArrayListDemo2 {
public static void main(String[] args) {
    // 創(chuàng)建集合對(duì)象
    // JDK7的新特性:泛型推斷。
    // ArrayList<Student> array = new ArrayList<>();
    // 但是我不建議這樣使用。
    ArrayList<Student> array = new ArrayList<Student>();

    // 創(chuàng)建元素對(duì)象
    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());
        }
    }
}

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容