泛型新体会、封装类与自动拆装箱

泛型新体会、封装类与自动拆装箱

一、泛型

泛型:
1.泛型是:类型 ---> 参数化,也就是传参
2.格式:
	public class 类名<泛型类型1,···>
    //该表达式也被称为钻石表达式,类型名一般推荐使用大写字母,T V K 等
	//不推荐使用小写字母或者是单词
3.< ? extends E >< ? super E >
    < ? extends E >
      a) ?E 的子类,两者都是引用类型
      b)其表示集合中的元素类型上限为 E 类型,即只能是 E 或者 E 的子类
      c)对比< ? extends Object >更容易理解
      d)< ? >< ? extends Object >的简写
    < ? super E >
      a) ?E 的超类、父类
      b)其表示集合中元素类型下限为 E 类型,即只能是 EE 的父类
代码展示
//使用泛型前
public class Node 
{
    int elment;
    Node next;

    public Node() 
    {
      
    }

    public Node(int elment, Node next) 
    {
        this.elment = elment;
        this.next = next;
    }
}

-------------------------------------------------------
  
public class HLinkedList 
{
    Node head;
    int size = 0;
    void add(int ele) 
    {
        if (head == null) 
        {
            head = new Node(ele,null);
        }
        Node curr = head;
        while (curr.next != null) 
        {
            curr = curr.next;
        }
        curr.next = new Node(ele,null);
        size++;
    }
}
//使用泛型后
public class Node<T> 
{
    T elment;
    Node next;

    public Node() 
    {
      
    }

    public Node(T elment, Node next) 
    {
        this.elment = elment;
        this.next = next;
    }
}

-------------------------------------------------------
  
public class HLinkedList<T> 
{
    Node head;
    int size = 0;
    void add(T ele) 
    {
        if (head == null) 
        {
            head = new Node(ele,null);
        }
        Node curr = head;
        while (curr.next != null) 
        {
            curr = curr.next;
        }
        curr.next = new Node(ele,null);
        size++;
    }
}

二、封装类与自动装箱、拆箱

1.基础数据类型及其对应的类
基本数据类型对应的类(包装类)
byteByte
shortShort
intInteger
longLong
floatFloat
doubleDouble
booleanBoolean
charCharacter
2.装箱与拆箱
int i = 10; //基础数据类型
Integer i = 10; //引用数据类型

Integer integer = new Integer(10); //装箱 pack
int s = integer.intValue(); //拆箱 unpack

Integer i = 1000; //装箱 => new Integer(1000);
int i1 = i; //拆箱 => i.intValue();

//装箱:基础数据类型 ----> 引用类型
//上述引例中 Integer 在装箱的过程中调用了 valueOf() 方法
//自动装拆箱:无需 new 对象,无需调用 intValue()
//基础类型可以直接转化为引用类型
//引用类型可以直接转化为基础类型

学习来源:来源一来源二来源三

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值