Java记录 -74- 自定义泛型

本文介绍了Java泛型的基本概念,包括单泛型与双泛型的使用方法,以及如何通过泛型实现集合的类型安全。此外,还展示了泛型类的具体实例,并通过模仿ArrayList实现了泛型化的集合。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

泛型:所谓泛型,就是变量的类型参数化。

作用:限制泛型可用类型。


  1. 简单的泛型定义使用:

public class GenericFoo<T> {    private T foo;        public void setFoo(T foo){        this.foo = foo;    }    public T getFoo(){        return this.foo;    }        public static void main(String[] args){        //GenericFoo is a raw type, References to generic type GenericFoo<T> should be parameterized.        GenericFoo foo = new GenericFoo();                 GenericFoo<String> sFoo = new GenericFoo<String>();        GenericFoo<Integer> iFoo = new GenericFoo<Integer>();                sFoo.setFoo("string foo");//        sFoo.setFoo(11); //这里只能放置String类型的,放置11在编译时就会报错。        iFoo.setFoo(11);    }}

2.定义两个泛型,以及泛型数组的定义使用:

public class GenericFoo2<T,E> {    private T foo1;    private E foo2;    private T[] arrays;        public T getFoo1() {        return foo1;    }    public void setFoo1(T foo1) {        this.foo1 = foo1;    }    public E getFoo2() {        return foo2;    }    public void setFoo2(E foo2) {        this.foo2 = foo2;    }    public T[] getArrays() {        return arrays;    }    public void setArrays(T[] arrays) {        this.arrays = arrays;    }    public static void main(String[] args){        GenericFoo2<String,Boolean> gf = new GenericFoo2<String,Boolean>();        gf.setFoo1("string");        gf.setFoo2(false);        gf.setArrays(new String[]{"aa","bb"});    }}

3.模仿ArrayList实现集合泛型化:

public class GenericCollection<E> {    private Object[] array;    private int index;        public GenericCollection(){        this(10);    }    public GenericCollection(int capacity){        array = new Object[capacity];    }        public void add(E e){        array[index++] = e;    }    public E get(int index){        return (E)array[index];    }        public static void main(String[] args){        GenericCollection<Integer> gc = new GenericCollection<Integer>();        for(int i=0;i<10;i++){            gc.add(i*2);        }        for(int i=0;i<10;i++){            System.out.println(gc.get(i));        }    }}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值