Java generics
One, the advantages and disadvantages of using generics
1. Don't use generics
advantage:
When creating a collection without declaring generics, the default is Object type, which can store any data type
Disadvantages:
Unsafe, will cause an exception
2. Use generics
advantage:
1. Avoid the trouble of type conversion, the stored types are consistent and easy to operate
. 2. The exceptions in the runtime are upgraded to the compile period to reduce unnecessary troubles in the later period
Disadvantages:
Can only store a specific type of data
Two, define an interface containing generics
/*
定义含有泛型的接口
*/
public interface GenericInterface<I> {
void method(I i);
}
public class Demo01 {
public static void main(String[] args) {
/*
在接口定义泛型,作为方法的参数使用
- 使用了匿名内部类和匿名对象
*/
new GenericInterface<String>(){
@Override
public void method(String s) {
System.out.println(s);
}
}.method("小斑马");
}
}
Three, contains generic classes and methods
1. Contain generic classes
/*
定义一个使用泛型的类
当不确定数据类型的时候可以使用泛型
创建对象时确定那种数据类型传递给泛型
*/
public class GenericClass<E> {
private E name;
public E getName() {
return name;
}
public void setName(E name) {
this.name = name;
}
}
2. Contain generic methods
/*
定义含有泛型的方法
格式:修饰符<泛型> 返回值类型 方法名(参数列表(使用泛型)){}
*/
public class GenericMethod {
public static void main(String[] args) {
method2("e");
}
//含有泛型的方法
public <M> void method1(M m){
System.out.println(m);
}
//含有泛型的静态方法
public static <N> void method2(N n){
System.out.println(n);
}
}
3. Use generic classes and methods
public class Demo01 {
public static void main(String[] args) {
demo01();
demo02();
}
/*
使用含有泛型的类
*/
private static void demo01() {
GenericClass<Integer> gc1 = new GenericClass();
gc1.setName(1);
System.out.println(gc1.getName()+12);
GenericClass<String> gc2 = new GenericClass();
gc2.setName("小斑马");
System.out.println(gc2.getName());
}
/*
使用含有泛型的方法
*/
private static void demo02() {
//使用含有泛型的方法
GenericMethod gm = new GenericMethod();
gm.method1("qwer");
gm.method1(1);
//使用含有泛型的静态方法
GenericMethod.method2(true);
GenericMethod.method2('小王');
}
}