泛型基本理解

泛型的简单理解

在不使用泛型时的代码。

public class MyLinkedList {
    Node head = null;
    int size;
    class Node {
        int data;
        Node next = null;
        public Node() {}
        public Node(int data) {
            this.data = data;
        }
    }
    public void add (int element) {
        if(head == null) {
            Node node = new Node(element);
            head = node;
        }
        Node current = head;
        while(current.next != null) {
            current = current.next;
        }
        current.next =  new Node(element);
    }
}
public class Test {
    public static void main(String[] args) {
        MylinkedList  a = new MylinkedList;
        a.add(10);
    }
}

在不使用泛型的时候,我们这个链表里只能存放int类型的数据,如果想存放String类型的数据时,我们只能通过重新修改MyLinkedList中的代码,这就造成了代码的重复。在java中,Sun公司为我们提供了一种方法可以不用这么麻烦,他就是泛型。

泛型

泛型就是把类型明确的工作推迟创建对象或者调用方法的方式。这个方式又称为参数化类型。

泛型的是使用方法分为三种,泛型类、泛型方法、泛型接口

泛型类
public class 类名< T >  //< T >钻石表达式

在上面的代码中我们就可以这么来写

public class MyLinkedList<T> {
    Node head = null;
    int size;
    class Node {
        T data;
        Node next = null;
        public Node() {}
        public Node(T data) {
            this.data = data;
        }
    }
    public void add (T element) {
        if(head == null) {
            Node node = new Node(element);
            head = node;
        }
        Node current = head;
        while(current.next != null) {
            current = current.next;
        }
        current.next =  new Node(element);
    }
}

在测试样例中

public class Test {
    public static void main(String[] args) {
        MylinkedList<int>  a = new MylinkedList<>;
         MylinkedList<String>  b = new MylinkedList<>;
        a.add(10);
        b.add("aaa");
    }
}

有了泛型,我们就不再需要麻烦的写重复代码。而是在创建对象的时候加入这个的类型就可以了。

泛型方法
public<泛型类型> 返回类型 方法名(泛型类型)
public class Test {
    public <T> void show(T t) {
        System.out.println(t);
    }
}
泛型接口
public interface 接口名<泛型类型1>

泛型可以将问题提前暴露,优化了程序的设计。泛型在编译的时候会被你指定的类型所替换,当你提供给的类型和你指定的类型不一致的时候,他会在编译时就报错。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值