/*
* 使用集合存儲自定義對象並遍歷
* 因爲集合能夠存儲任意類型的對象,當咱們存儲了不一樣類型的對象,就有可能在轉換的時候出現類型轉換異常,
* 因此java爲了解決這個問題,給咱們提供了一種機制,叫作泛型
*
* 泛型:是一種普遍的類型,把明確數據類型的工做提早到了編譯時期,借鑑了數組的特色
* 泛型好處:
* 避免了類型轉換的問題
* 能夠減小黃色警告線
* 能夠簡化咱們代碼的書寫
*
* 何時能夠使用泛型?
* 問API,當咱們看到<E>,就能夠使用泛型了
*
*/java
public class GenericDemo { public static void main(String[] args) { //建立集合對象 Collection<Student> c = new ArrayList<Student>(); //建立元素對象 Student s = new Student("zhangsan",18); Student s2 = new Student("lisi",19); //添加元素對象 c.add(s); c.add(s2); //遍歷集合對象 Iterator<Student> it = c.iterator(); while(it.hasNext()) { //String str = (String)it.next(); //System.out.println(str); Student stu = it.next(); System.out.println(stu.name+" "+stu.age); } //Student<StringBuilder> st1=new Student<StringBuilder>("張三", 20); } } class Student { String name; int age; public Student(String name,int age) { this.name = name; this.age = age; } }