In daily life, we often use generics, but generic data sometimes reports some inexplicable errors, and some syntax such as wildcards and the actual operation method of generics in the virtual machine are also worth studying. , today we will discuss generics together.
Before Java added generics, inheritance was used to handle programs that now use generic operations.
ArrayList files = new ArrayList();String filename = (String) files.get(0); ArrayList<String> files2 = new ArrayList<>(); //后一个尖括号中的内容可以省略,在1.7之后String filename2= files2.get(0);String addname = "addname"; files2.add(addname); //在add函数调用之时,ArrayList泛型会自动检测add的内容是不是String类型 files2.add(true); //报错 The method add(String) in the type ArrayList<String> is not applicable for the arguments (boolean)
For example, the ArrayList class only maintains an array of Object references. Type conversion is required when obtaining the value (the first two lines above), and there is no guarantee when passing in content. With generics, this data structure becomes convenient, readable and safe. We can see at a glance that the type stored in the ArrayList
In addition, one thing I want to point out is that there are no errors in the first two lines of the above code. Because in ArrayList, it is okay not to use <>. There are still many restrictions on generic classes. When necessary, the ArrayList class is also used.
Let’s take a simple generic class directly:
public class Pair<T> { private T first; private T second; public Pair() { first = null; second = null; } public Pair(T first, T second) { this.first = first; this.second = second; } public T getFirst() { return first; } public void setFirst(T first) { this.first = first; } public T getSecond() { return second; } public void setSecond(T second) { this.second = second; } }
In fact, a generic class can be regarded as an ordinary class Factory, just replace T with the type we need. Then for situations where two types are required, we only need to write Pair
The above example is too simple and cannot do any substantial work, so please think about this question. If we add a function to the above generic class:
public T min(T[] array) {...}//返回传入数组中的最小值
So at this time, if we want to implement this function, we must at least ensure that T type objects can be compared in size. How to detect this situation? In fact, we can solve this problem by setting limits on the type variable T.
public <T extends Comparable>T min(T[] array){...}//T如果没有实现compare方法则报错不执行min函数
<T extends Comparable>
You can probably guess the meaning, which is that the type variable T is required to inherit the Comparable interface. Now the generic min method can only be called by arrays of classes that implement the Comparable interface (such as String, Date...), and other classes will generate a compilation error.
Same, there can also be multiple restrictions: <T, U extends Comparable&Serializable>
are also allowed. Commas are used to separate type variables, and & is used to separate qualified types.
In fact, Comparable itself is a generic interface. In order for the above content to be easily understood, we pretend to be confused and think that it is not a generic interface. But it should be noted that the actual correct way to write the above is:
> instead of <T extends Comparable>
Generics defined in a generic class are valid in the entire class. That is to say, after the object of the generic class determines the specific type to be operated, all the types to be operated are already fixed. For example, ArrayList
public <T> T getMid(T[] array){ return array[array.length/2]; }
For example, in the getMid function above, adding <T>
in front of the return value T turns it into a generic method. Please note that it is in a ordinary class, and generic methods do not necessarily have to exist in generic classes. The following is an example of calling a generic method. When calling a generic method, the compiler will infer the called method based on the following type, so there is no need to explicitly indicate what type T is:
String mid = ArrayAlg.getMid("Jone" , "Q" , "Peter"); //okdouble mid2 = ArrayAlg.getMid(3.14 , 25.9 , 20); //error,编译器会把20自动打包成Integer类型,而其他打包成Double类型,我们尽量不要让这种错误发生
In ordinary classes, we can flexibly call different type parameters through the above generic methods. In generic classes, do we need such flexible generic methods? I think it's not needed. We provide type parameters for generic classes. In fact, we rarely use other types in one type. If we must use them, we generally use the method of multiple type parameters such as Pair
So what is the use of generic methods in generic classes? We can use generic methods in generic classes to limit generic variables. For example, the <T extends Comparable>
T method we mentioned above can only be used by T with the Comparable interface. Otherwise something will go wrong.
@SuppressWarnings("hiding") public static <T extends Comparable<?> & Serializable> T min(T[] array) {...}
java虚拟机中没有泛型类型对象——所有的对象都属于普通类,那么虚拟机是怎么用普通类来模拟出泛型的效果呢?
只要定义了一个泛型类,虚拟机都会自动的提供一个原始类型。原始类型的名字就是删除类型参数的泛型类的名字。擦除类型变量,并替换为第一个限定类型(如果没有限定则用Object来替换)。
比如,我们在一开始给出的简单泛型类Pair<T>在虚拟机中会变成如下的情况:
public class Pair { private Object first; private Object second; public Pair() { first = null; second = null; } public Pair(Object first, Object second) { this.first = first; this.second = second; } public Object getFirst() { return first; } public void setFirst(Object first) { this.first = first; } public Object getSecond() { return second; } public void setSecond(Object second) { this.second = second; } }
这就是擦除了类型变量,并且将没有限制的T换成Object之后的情况,如果有限定类型,比如,我们的泛型类是Pair
public class Pair { private Compararble first; private Compararble second; public Pair() { first = null; second = null; } public Pair(Compararble first, Compararble second) { this.first = first; this.second = second; } public Compararble getFirst() { return first; } public void setFirst(Compararble first) { this.first = first; } public Compararble getSecond() { return second; } public void setSecond(Compararble second) { this.second = second; } }
那么既然类型都被擦除了,类型参数也被替换了,怎么起到泛型的效果呢?当程序调用泛型方法时,如果返回值是类型参数(就是返回值是T),那么编译器会插入强制类型转换:
Pair<String> a = ...; String b = a.getFirst();//编译器强制将a.getFirst()的Object类型的结果转换为String类型
编译器将上述过程翻译位两条虚拟机指令:
- 对原始方法Pair.getFirst的调用。
- 将返回的Object类型强制转换为String类型。
对于类型擦出也出现在泛型方法中,但是泛型方法中的擦除带来很多问题:
//----------------类A擦除前----------------------class A extends Pair<Date>{ public void setSecond(Date second){...} }//----------------类A擦除后----------------------class A extends Pair{ public void setSecond(Date second){...} }
从上面的代码中,我们可以看出,类A重写了Pair
public Class Pair{ public void setSecond(Object second){...} }
突然发现,父类Pair中的setSecond方法参数变为Object,和子类中的参数不同。擦除之后,父类的setSecond方法和子类的setSecond方法完全变为两个不一样的方法!这就没有了重写之说,那么接着考虑下面的语句:
A a = new A();Pair<Date> pair = a;pair.setSecond(new Date()); //当pair去调用setSecond函数时,有两个不一样的setSecond函数可以被调用,一个是父类中参数为Object的,一个是子类中参数为Date的。
第三行的调用出现了两种情况,这绝对不是我们想要的结果,我们开始的时候只是重写了父类中的setSecond方法,但是现在有两个不同的setSecond方法可以被使用,而且这时编译器不知道要去调用哪个。
为了防止这种情况的发生,编译器会在A类(子类)中生成一个桥方法:
//------------桥方法-------------- public void setSecond(Object second){ setSecond((Date)second); }
这个桥方法,让Object参数的方法去调用Date参数的方法,从而将两个方法合二为一,这个桥方法不是我们自己写的,而是在虚拟机中自动生成的,让代码变得安全,让运行结果变得符合我们的期望。
当两个有关系的类分别作为两个泛型类的类型变量的时候,这两个泛型类是没有关系的。这个时候如果需要涉及到继承规则之类的内容时,那么就需要使用通配符——“?”。
有的时候两个类间有继承关系,但是分别作为泛型类型变量之后就没了关系,在函数调用和返回值的时候,这种不互通尤为让人头痛。好在通配符的上下界限定类型为我们安全的解决了这个难题。 ? super A
的意思是“?是A类型的父类型”,? extends A
的意思是“?是A类型的子类型”。
既然知道了意思,我们看一下下面这四种用法:
public static void printA (Pair<? super A> p) {...} //ok public static void printA (Pair<? extends A> p) {...} //error public static Pair<? extends A> printA () {...} //ok public static Pair<? super A> printA () {...} //error
为什么四种中有两种有错误呢?
实际上,要牢记这句话:带有超类型限定的通配符可以向泛型对象写入(做参数),带有子类型限定的通配符可以从泛型对象读取(做返回值)。道理这里就不详细讲了,如果有兴趣研究的话可以思考一下,思考的方向无非是继承关系之间的引用转换,只有上面两行ok的方法才是转换安全的。现在我们可以试着去理解上面的
无限定通配符的用法其实很单一。无限定通配符修饰的返回值只能为Object,而其做参数是不可以的。那么无限定通配符的用处在哪里呢?源于他的可读性好。
public static boolean hasNulls(Pair<?>){...}
上面的代码的意思是对于任何类型的Pair泛型判断是否为空,这样写比用T来表示可读性确实好的多。
八大基本类型务必要使用包装类来实例化,否则泛型参数一擦除我们就傻眼了,怎么把int的数据放到Object里面呢?
参数化的类型数组是不能被创建的。我们完全可以用多个泛型嵌套来避免这种情况的发生,如果创建了泛型数组,擦除之后类型会变成Object[ ],如果有一个类型参数不同的泛型存入这个数组时,因为都被擦除成Object,所以不会报错,导致了错误的发生。需要说明的是,只是不允许创建这些数组,而声明类型为Pair
要记住在虚拟机中,每个对象都有一个特定的非泛型类。所以,所有的类型查询只产生原始类型。比如:
if(a instanceof Pair<String>) //只能测试a是否是任意类型的一个Pair Pair<String> sp = ...; sp.getClass(); //获得的也是Pair(原始类型)
有的时候我们需要将类型变量实例化成它自己本身的类型,但是一定要注意写法,不可以直接实例化类型变量:
public Pair() { this.first = new T();//错误,类型擦除后T变成Object,new Object()肯定不是想要的 this.first = T.class.newInstance();//错误,T.class是不合法的写法}
上述的两种写法都是错的,如果一定要这样做的话,也只能在调用泛型类的时候构造出一个方法(构造的方法不在泛型类中,在调用泛型类的普通类中),将你要用的类型作为参数传进去,想办法来实例化。
不能在静态域中引用类型变量,静态方法本来就是和对象无关,他怎么能知道你传进来的是什么类型变量呢?
既不能抛出也不能捕获泛型对象。事实上,甚至泛型类扩展Throwable都是不可以的,但是平时我们不去编写泛型类的时候,这一条并不需要注意过多。
当两个有关系的类分别作为两个泛型类的类型变量的时候,这两个泛型类是没有关系的。这个时候如果需要涉及到继承规则之类的内容时,一定要使用通配符,坚决不要手软。
泛型类的静态方法因为是静态,所以也不能获得类型变量,在这个时候唯一的解决办法是——所有的静态方法都是泛型方法。
? t = p.getA(); //error
所有用“?”来作为类型的写法都是不被允许的,我们需要用T来作为类型参数,有必要的时候可以做一个辅助函数,用T类型来完成工作,用?通配符来做外面的包装,既达到了目的,又提高了可读性。
泛型为我们提供了许许多多的便利,包装出来的很多泛型类让我们能更快速安全的工作。而泛型的底层实现原理也是很有必要研究一下的,一些需要我们注意的事项和通配符的使用,此类细节也确实有许多值得我们学习之处。
在日常生活中,我们经常用到泛型,但是泛型数据有些时候会报一些莫名其妙的错,而且一些通配符等语法、泛型在虚拟机中的真正操作方式也有我们值得研究之处,今天我们就一起来讨论一下泛型。
以上就是java泛型综合详解的内容,更多相关内容请关注PHP中文网(m.sbmmt.com)!