数据结构(泛型)
1,装箱
int i = 10;
Integer j = Integer.valueOf(i);
2.拆箱
Integer i = 10;
int j = i.intValue();
3.自动装箱
int i = 10;
Integer j = i;
int i = 10;
Integer j =(Integer) i;
4,自动拆箱
Integer i =10;
int j = i;
Integer i =10;
int j = (int) i;
有一段代码需要解析一下:
public static void main(String[] args) {
Integer a = 127;
Integer b = 127;
Integer c = 128;
Integer d = 128;
System.out.println(a == b);
System.out.println(c == d);
}
该过程涉及到了装箱操作,所以我们得追究到valueOf方法
我们发现对于i有一个取值范围,也就是最大值和最小值,而他的存储方式就是再一个数组中存储,这个数组的大小就是low+high+1,
我们发现low为-128,high为127。在存储数据时是这样的。
i+(-low),一旦超过数组大小,相当于重新创建了一个对象,这也就解释了我们的那道题。其实就是装箱搞得鬼。
泛型
泛型适用于多种类型,比如泛型数组就可以存放不止一种类型的数据。
class Func1{
Object[] array = new Object[10];
public Object getArray(int pos) {
return (Object) array[pos];
}
public void setArray(int pos, Object num) {
this.array[pos] = num;
}
}
public class demo5 {
public static void main(String[] args) {
Func1 func1 = new Func1();
func1.setArray(0,"zhangsan");
System.out.println(func1.getArray(0));
func1.setArray(1,3232);
System.out.println(func1.getArray(1));
}
}
我们发现泛型可以存储不同类型的数据,但在get方法中我们得进行一个强制类型转换,一般情况下我们使用泛型是为了指定当前容器为特定的数据类型,用泛型来做检查,为什么呢?我们来看下面的实例。
class Func1<T>{
T[] array = (T[]) new Object [10];
public T getArray(int pos) {
return (T) array[pos];
}
public void setArray(int pos, T num) {
this.array[pos] = num;
}
}
public class demo5 {
public static void main(String[] args) {
Func1<String> func1 = new Func1<>();
func1.setArray(0,"zhangsan");
System.out.println(func1.getArray(0));
func1.setArray(1,111);
System.out.println(func1.getArray(1));
}
}
这里的T代表这是一个泛型类,可以看到在经过我们改造后的代码,变得不能存储多种类型的数据了,这里我们再声明字符串类型后,后续设置整形,直接报错,这就是泛型的检查作用,使得当前同期只能存储特定的类型。
接下来我们得看看为何在实例化泛型类的数组时会报错。
因为程序觉得不能确定里面的类型是一致的,觉得不安全,所以报错。
对于这种写法我们可以改一改。
这一出了对于强制类型转换的潜在风险。
擦除机制
在没有指定的泛型上界时,程序在编译时会将T替换为Object。
如果上界是 Number则泛型参数类型不能是String,因为它不是Number的子类,Integer则可以。
上界也可以实现接口,比如 求最大值。