泛型


泛型:泛型是一种把类型明确的工作推迟到创建对象或者调用方法的时候才去明确的特殊的类型.类型化参数,把类型当作参数一样的传递.
     格式:
        <数据类型>
        此处的数据类型只能是引用类型.
  
     好处:
        A:把运行时期的错误提早到编译期间
        B:避免了强转类型

 

        C:优化了程序设计,解决了黄色警告线

 

        泛型一般在集合中使用

        早期使用Object来代表任意的类型

 

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

/*
 * 泛型一般在集合中使用
 * */

public class ArrayListDemo {

	public static void main(String[] args) {
		// 用 ArrayList存储字符串并遍历.用泛型改进.
		ArrayList<String> arr = new ArrayList<String>();
		arr.add("hello");
		arr.add("world");
		arr.add("java");
		Iterator<String> it = arr.iterator();
		while (it.hasNext()) {
			String s = it.next();
			System.out.println(s);
		}
	}

}

泛型类

package four;

/*
 * 	泛型类:把泛型定义在类上
 * 
 * */

public class ObjectTool<T> {
	private T obj;

	public T getObj() {
		return obj;
	}

	public void setObj(T obj) {
		this.obj = obj;
	}
}
//测试

public class ObjectToolDemo {
	public static void main(String[] args) {
		ObjectTool<String> ot = new ObjectTool<String>();
		ot.setObj("周杰伦");
		String s = ot.getObj();
		System.out.println(s);

	}
}

泛型方法:把泛型定义在方法上

public class ObjectTool {
	public <T> void show(T t) {
		System.out.println(t);
	}
}

 

public class ObjectTooldemo {

	public static void main(String[] args) {
		ObjectTool ot = new ObjectTool();
		ot.show("ss");
		ot.show(210);
		ot.show(true);
	}}

 

把泛型定义在接口上

 

public interface Inter<T> {
	public abstract void show(T t);

}
public class InterDemo {
	public static void main(String[] args) {
//		// 第一种情况
//		Inter<String> i = new InterImpl();
//		i.show("风清扬");
//	
		//第二种
		Inter<String> i = new InterImpl<String>();
		i.show("hello");
		Inter<Integer> i2 = new InterImpl<Integer>();
		i2.show(100);
	}
}

 

/*
 * 实现类在实现接口的时候
 * 	两种情况
 * 第一种:已经知道什么类型 
 * 第二种:不知道什么类型
 * */
//第一种
//public class InterImpl implements Inter<String> {
//
//	@Override
//	public void show(String t) {
//		System.out.println(t);
//	}
//
//}
//第二种
public class InterImpl<T> implements Inter<T> {

	@Override
	public void show(T t) {
		System.out.println(t);
	}
}

 

泛型高级(通配符)

 

 
<?>:表示任意的类型都是可以的
<? extends E>:向下限定, E及其子类
<? super E>:向上限定,E及其父类
  
 泛型如果明确写的时候,前后必须一致
 
 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值