泛型入门

xiaoxiao2021-02-27  496

泛型: 自我理解是一种提前明确并规定数据类型的一种方法。 用代码可以直观的表示出泛型的基本用法:

public static void main(String[] args) { //创建一个集合 // ArrayList al = new ArrayList(); // al.add("hello"); // al.add("world"); // al.add("java"); // al.add(100); //创建ArrayList集合的时候就给集合加上泛型,明确一下这个的类型 //在这里已经明确了数据类型,说明目前只能给al集合中添加String类型的元素 ArrayList<String> al = new ArrayList<String>(); al.add("java"); al.add("hello"); al.add("world"); //al.add(100); 报错!

泛型也可以指定自定义对象。

public static void main(String[] args) { //创建集合对象并加上泛型 //创建学生对象 Student s = new Student("a", 11); Student s1 = new Student("b", 22); Student s2 = new Student("c", 33); //创建集合对象并加上泛型 List<Student> list = new ArrayList<Student>(); //集合中添加元素 list.add(s); list.add(s1); list.add(s2); //使用迭代器进行遍历 Iterator<Student> it = list.iterator(); while (it.hasNext()) { //取出迭代器中的元素 Student ss = it.next(); System.out.println(ss.getAge()+" "+ss.getName()); } }
转载请注明原文地址: https://www.6miu.com/read-267.html

最新回复(0)