数据结构学习1 初识泛型

装箱和拆箱

装箱/装包: 把一个基本数据类型转变为包装类型

拆箱/拆包: 把一个包装类型转变为一个基本数据类型

        int a = 1;
        Integer i = a;
        // 自动装箱

        int b = i;
        // 自动拆箱

        Integer ii = Integer.valueOf(a);
        // 手动装箱,推荐使用 Integer.valueOf() 而不是 new Integer()

        int bb = ii.intValue();
        // 手动拆箱

自动装箱和自动拆箱

{
        int a = 1;
        //Integer ii = a; //自动装箱
        Integer ii = Integer.valueOf(a);
//        Integer ii2 = new Integer(2);
        Integer ii2 = Integer.valueOf(2);
        int b = ii2; //自动拆箱
        System.out.println(a);
        System.out.println(b);
    }

反汇编

new的时候调用了init构造方法

{
        Integer ii = 100;
        Integer ii2 = 100;
        System.out.println(ii == ii2);
    }

运行结果为

{
        Integer ii = 200;
        Integer ii2 = 200;
        System.out.println(ii == ii2);
    }

运行结果为

这是为什么呢

这既然是包装类型 , 那么可能调用了valueOf方法

可以看到最小值为-128

进入IntegerCache

最大值为128

如果在-128到127之间

那么返回的是下标为 i + 128的数组的值

因为存储的是-128到127

泛型

泛型在c++中叫做模版

引出泛型

实现一个类,类中包含一个数组成员,使得数组中可以存放任何类型的数据,也可以根据成员方法返回数组中某个下标的值?

使用Object类型

class Myarray {
    public Object[] array = new Object[10];
    
    public void setValue(int pos, int val) {
        array[pos] = val;
    }
    public Object getValue(int pos) {
        return array[pos];
    }
}

代码定义了一个名为 Myarray 的类,其中有一个包含 Object 类型的数组 array,并提供了设置和获取数组元素值的方法。

然而,虽然数组的类型是 Object[],但 setValue 方法中将一个 int 类型的值直接赋给数组元素。这是因为数组的元素类型是 Object,而 int 是基本数据类型。在这种情况下,会发生自动装箱,将 int 装箱为 Integer

即不能放任意类型的元素

将setValue改为

public void setValue(int pos, Object val) {
        array[pos] = val;
    }

可以使用该数组存放任意类型的数据了

但是

为什么不能给String类型呢?

因为Object是String的父类类型

改为

String str = (String) myarray.getValue(2);

不过这数组中存放的是String类型

怎么又强转起来了?

感觉多此一举了

现在看看自己的目的:存放任何类型的数据,也可以根据成员方法返回数组中某个下标的值

现在把类型改为

class Myarray<T> 
public T[] array = new T[];但是不能new一个 T 类型的数组

改成

public T[] array = (T[]) new Object[10];

暂时骗过编译器

可以发现不报错了

这里我觉得, 个人理解, T像是一个占位符 可以放String 也可以放Integer类型 (包装类型, 除了int是Integer , char是Character之外 其他都是本身大写)

总结

泛型的意义: 

1. 在编译的时候 检查数据类型是否正确

2. 在编译的时候, 帮助进行类型转换

补充:

要是

Myarray<Person> myarray1 = new Myarray<>();

改为

Myarray myarray1 = new Myarray();呢

是不会报错的

这种类型叫做裸类型

上面泛型的代码也可以写为

class Myarray<T> {
//    public T[] array = (T[]) new Object[10];

    public Object[] array = new Object[10];
    public void setValue(int pos, T val) {
        array[pos] = val;
    }
    public T getValue(int pos) {
        return (T) array[pos];
    }
}

有帮助的话记得点个赞哦

  • 8
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值