JAVA基础之泛型应用

JAVA基础之泛型应用

泛型:JDK1.5版本以后出现新特性。用于解决安全问题,是一个类型安全机制。
好处
1、将运行时期出现问题ClassCastException,转移到了编译时期,方便于程序员解决问题。让运行时问题减少,安全!
2、避免了强制转换麻烦。
通常在集合框架中很常见,
只要见到<>就要定义泛型。
其实<> 就是用来接收类型的。
当使用集合时,将集合中要存储的数据类型作为参数传递到<>中即可。

泛型定义在集合中

<span style="font-size:18px;">	public static void main(String[] args) 
	{
		ArrayList<String> al = new ArrayList<String>();//通过<>来定义要操作的引用数据类型。
		al.add("abc01");
		al.add("abc0991");
		al.add("abc014");
		Iterator<String> it = al.iterator();
		while(it.hasNext())
		{
			String s = it.next();
			System.out.println(s+":"+s.length());
		}
	}</span>

泛型定义在接口上

<span style="font-size:18px;">interface Inter<T>
{
	void show(T t);
}
class InterImpl<T> implements Inter<T>
{
	public void show(T t)
	{
		System.out.println("show :"+t);
	}
}
class GenericDemo 
{
	public static void main(String[] args) 
	{
		InterImpl<Integer> i = new InterImpl<Integer>();
		i.show(4);
	}
}</span>

泛型定义在类上

<span style="font-size:18px;">class DemoT<T>
{
	public  void show(T t)
	{
		System.out.println("show:"+t);
	}
	public <Q> void print(Q q)
	{
		System.out.println("print:"+q);
	}
	public  static <W> void method(W t)
	{
		System.out.println("method:"+t);
	}
}
class GenericDemo
{
	public static void main(String[] args) 
	{
		DemoT <String> d = new DemoT<String>();
		d.show("haha");
		d.print(5);
		d.print("hehe");
		DemoT.method("hahahahha");
	}
}</span>



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值