泛型的好处
package generics;
/**
* Created by lipei on 2017/5/1.
*/
public class NoGenericsDemo {
public static void main(String[] args) {
Wrapper w1 = new Wrapper(123);
Wrapper w2 = new Wrapper("1234");
Wrapper w3 = new Wrapper(Long.valueOf("1234567890"));
System.out.println(w1);
System.out.println(w2);
System.out.println(w3);
//放进去没有错误,取出也没有问题,但是运行时就会出问题
String w11 = (String) w1.getContent();
System.out.println("w11 =" + w11);
}
}
class Wrapper{
public Object content;
public Wrapper(Object content) {
this.content = content;
}
public Object getContent() {
return content;
}
public void setContent(Object content) {
this.content = content;
}
@Override
public String toString() {
return "Wrapper{" +
"content=" + content +
'}';
}
}
什么是泛型
- 实现了参数化类型的概念,是代码可以应 用于多种类型
- 可以用在类、接口和方法的创建中,分别 称为泛型类、泛型接口、泛型方法
- 当创建类型化参数时,编译器会负责转换 操作
通过泛型优化
package generics;
/**
* Created by lipei on 2017/5/1.
*/
public class GenericsDemo {
public static void main(String[] args) {
Wrapper02<Integer>w1 = new Wrapper02(123);
Wrapper02 w2 = new Wrapper02("1234");
Wrapper02 w3 = new Wrapper02(Long.valueOf("1234567890"));
System.out.println(w1);
System.out.println(w2);
System.out.println(w3);
//在类型初始化的时候已经告知是什么类型,故运行时不会出错
Integer w11 = w1.getContent();
System.out.println("w11 =" + w11);
}
}
class Wrapper02<T>{
public T content;
public Wrapper02(T content) {
this.content = content;
}
public T getContent() {
return content;
}
public void setContent(T content) {
this.content = content;
}
@Override
public String toString() {
return "Wrapper{" +
"content=" + content +
'}';
}
}
声明与使用泛型接口
package generics;
/**
* Created by lipei on 2017/5/1.
*/
public interface GenericsInterface<T> {
public T update (T t);
}
class test01 implements GenericsInterface <String>{
@Override
public String update(String s) {
return null;
}
}
class test02 implements GenericsInterface<Integer>{
@Override
public Integer update(Integer integer) {
return null;
}
}
网友评论