泛型集合的使用

发布于:2022-12-21 ⋅ 阅读:(421) ⋅ 点赞:(0)
package aggregate.MyGeneric.demo04;

import aggregate.ArrayList.Student;

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

public class Demo01 {
    public static void main(String[] args) {
        ArrayList<String> arrayList = new ArrayList<String>();
        arrayList.add("一花");
        arrayList.add("二乃");
        arrayList.add("三玖");
        arrayList.add("四叶");
        arrayList.add("五月");
        arrayList.add("上杉风太郎");
        //arrayList.add(200);因为上面是String类型的
        for (String string :arrayList)
             {
                 System.out.println(string);
             }
        ArrayList<Student> arrayList1= new ArrayList<>();
        aggregate.ArrayList.Student student = new aggregate.ArrayList.Student("炎柱",20);
        aggregate.ArrayList.Student student1 = new aggregate.ArrayList.Student("水柱",20);
        aggregate.ArrayList.Student student2 = new aggregate.ArrayList.Student("蛇柱",20);
        arrayList1.add(student);
        arrayList1.add(student1);
        arrayList1.add(student2);
        Iterator<aggregate.ArrayList.Student> iterator = arrayList1.iterator();
        while(iterator.hasNext()){
            aggregate.ArrayList.Student s = iterator.next();
            System.out.println(s.toString());
        }


    }
}
  • 泛型类可以指定,第一个代码就是指定指定代码,指定它的类型为String类型,所以下面的foreach循环也就为String类型
  • 因为是String类型,所以不可以添加除了字符串以外的类型
  • 第二行代码,可以添加在泛型里面添加某一个类,比如Student类,然后Student类里面的构造方法就被享用,然后实例化对象,再用add方法添加实例化后的对象,最后用迭代器Iterator输出,这里也需要添加一个Student的泛型类,因为需要用到toString方法
本文含有隐藏内容,请 开通VIP 后查看