泛型:泛型是一种把类型明确的工作推迟到创建对象或者调用方法的时候才去明确的特殊的类型.类型化参数,把类型当作参数一样的传递.
格式:
<数据类型>
此处的数据类型只能是引用类型.
好处:
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及其父类
泛型如果明确写的时候,前后必须一致