创建集合对象,使用泛型
好处:
1.避免了类型转换的麻烦,存储的是什么类型,取出的就是什么类型
2.把运行期异常(代码运行之后会抛出的异常),提升到了编译期(写代码的时候会报错)
弊端:
泛型是什么类型,只能存储什么类型的数据
代码举例:
private static void show1() { ArrayList arrayList = new ArrayList(); arrayList.add("abc"); arrayList.add(1); Iterator iterator = arrayList.iterator(); while (iterator.hasNext()){ Object next = iterator.next(); System.out.println(next); String s = (String)next; System.out.println(s.length()); } }
定义和使用含有泛型的类:
定义一个含有泛型的类,模拟Arraylist集合
泛型是一个未知的数据类型,当我们不确定什么什么数据类型的时候,可以使用泛型
泛型可以接收任意的数据类型,可以使用Integer,string, student. . .
创建对象的时候确定泛型的数据类型
代码举例:
public class GenericClass<E> { private E name; public E getName() { return name; } public void setName(E name) { this.name = name; } } public static void main(String[] args) { GenericClass genericClass = new GenericClass(); genericClass.setName("字符串"); Object obj = genericClass.getName(); GenericClass<Integer> objectGenericClass = new GenericClass<>(); objectGenericClass.setName(1); Integer name = objectGenericClass.getName(); System.out.println(name); }
搜索定义一个含有泛型的类,模拟ArrayList集合定义一个含有泛型的类,模拟ArrayList集合定义一个含有泛型的类,模拟ArrayList集合
复制
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)