CLASS NOTE - WEEK 5 - Generics and Autoboxing
01 Autoboxing and Unboxing
8 primitive types : all other types are reference types.
- 每一个primitive type都对应着相应的reference type,这些reference type被称为"wrapper classes".
- Java可以直接convert primitive & reference type,这个过程就是box和unbox:如果本应该传入的是一个wrapper type,但输入的是一个primitive type (like int),java就会autobox (the integer);同理要是本该传入一个primitive type而输入的是一个wrapper type,也能够自动unbox掉。
- 有3点注意事项:
Arrays是不可以autobox或者auto-unbox的,if you have an array of integers int[] x, and try to put its address into a variable of type Integer[], the compiler will not allow your program to compile.
Autoboxing和unboxing会有一定的performance影响,code that relies on autoboxing and unboxing will be slower than code that eschews such automatic conversions.
wrapper types会比primitive types占用更多的内存。
Widening :
- Java可以自动widen a primitive if needed.
- If you want to go from a wider type to a narrower type, you must manually cast.
02 Immutability
- An immutable datatype is a data type whose instances cannot change in any observable way after instantiation, e.g: String.
- Mutable datatypes include objects like
ArrayDeque
andPlanet
.We can add or remove items from an ArrayDeque, which are observable changes. Similarly, the velocity and position of a Planet may change over time. - 任何没有标记private的datatype都是mutable的,除非这些variables有被declared final. 这是因为一个outside的method可以改变non-private variables的value。但是!!!,Declare a reference as final是不能令object point to immutable的。
java public final ArrayDeque<String>() deque = new ArrayDeque<String>();
代码里的deque
variable是final的不能被reassigned,但deque point to什么是可以改变的。所以Declare a reference as final是不能令object point to immutable的。
03 Generics
Generics class
- Generics class本身在class的申明时就会将generics变量显示出来,因此整个class里面的变量和方法都可以用到generics。
Generics method
- 如下代码所示,Generics method只需要在方法声明的时候加入Generics变量就可以了。
public static <K,V> V get(Map61B<K,V> map, K key) {
if map.containsKey(key) {
return map.get(key);}return null;
}
- Generics的method在进行比较的时候,不能随意使用
> < ==
进行比较,且由于是Generics类型的变量(不是所有的objects都有compareTo method),在使用compareTo时需要提前给Generics类型的变量extends Comparable,如下代码所示。
public static <K extends Comparable, V> K maxKey(ArrayMap<K,V> map) {
List<K> l = map.keys();K result = l.get(0);for(int i = 1; i < l.size(); i++) {
if(l.get(i).compareTo(result) > 0) {
result = l.get(i);}}return result;}
- Built in Java Interface:
Comparable<T>
, implemented by integer, string, etc. - 为什么是extend而不是implement?正常的extends用法是继承upper class的全部方法并且可以扩展;但是当我们用在这里
K extends Comparable
时,we are simply stating a fact. 我们并没有给到K与Comparable相关的ability,我们只阐述K must be Comparable–>在使用generics时 (like in generic method headers), extends是一种限制,不能赋予新的ability.
Generics Summary
- Generics的四个特点:
1)Autoboxing和auto-unboxing转换primitive和wrapper type很方便;
2)primitive types之间的转换;
3)方法的generic类型(generic method)的应用;
4)Type upper bounds in generic methods (e.g.K extends Comparable<K>
)