泛型集合
package com.tiedandan.集合.泛型.泛型集合;
//泛型集合
/**
* ArrayList类源码就是泛型类,在调用时可以指定对象的类型。
* 这样做的好处是可以强制一个集合只有一种类型的数据。
* 如果不用泛型强制,则集合中不同类型的数据会引发遍历错误
*
*/
import java.util.ArrayList;
import java.util.Iterator;
public class GenericList {
public static void main(String[] args) {
ArrayList<String> arrayList = new ArrayList<String>();//指定arrylist里面只能放string类型
Student stu1 = new Student("张铁蛋1");
Student stu2 = new Student("张铁蛋2");
Student stu3 = new Student("张铁蛋3");
Student stu4 = new Student("张铁蛋4");
arrayList.add("李狗蛋");
arrayList.add("张铁蛋");
ArrayList<Student> arrayList2 = new ArrayList<Student>();//指定ArrayList里面只能放Student类型
arrayList2.add(stu1);
arrayList2.add(stu2);
arrayList2.add(stu3);
arrayList2.add(stu4);
System.out.println("---------输出arrayList----------");
for (String s : arrayList) {
System.out.println(s.toString());
}
System.out.println("---------输出arrayList2------------");
for (Student student : arrayList2) {
System.out.println(student.toString());
}
System.out.println("----------用迭代器进行遍历----------");
//用迭代器进行遍历
Iterator<Student> lit= arrayList2.iterator();
while (lit.hasNext()){
Student s =lit.next();
System.out.println(s.toString());
}
}
}
package com.tiedandan.集合.泛型.泛型集合;
public class Student {
public Student() {
}
private String name;
private int age;
public Student(String name){
this.name= name;
}
public Student(String name, int age) {
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;
}
运行结果:
---------输出arrayList----------
李狗蛋
张铁蛋
---------输出arrayList2------------
Student{name='张铁蛋1', age=0}
Student{name='张铁蛋2', age=0}
Student{name='张铁蛋3', age=0}
Student{name='张铁蛋4', age=0}
----------用迭代器进行遍历----------
Student{name='张铁蛋1', age=0}
Student{name='张铁蛋2', age=0}
Student{name='张铁蛋3', age=0}
Student{name='张铁蛋4', age=0}