JavaDS--模拟实现ArrayList

Object类 是所有类的父类
基类的引用可以指向所有子类
例如:Object o = new String();

自己创建的MyArrayList

Person p = (Person)L1.get(0);
向下转型:不安全
get()方法返回值为Object类型,需转换为Persen类型

class Person{
    public void Print(){
        System.out.println("我是一个好人");
    }
}
class MyArrayList
{

    Object[] array;
    int capacity;  // 空间的总大小
    int size;      // 空间中存储有效元素的个数

    public MyArrayList(int capacity){
        array = new Object[capacity];
        size = 0;
        this.capacity = capacity;
    }

    void add(Object e)
    {
        // 检测容量
        array[size++] = e;
    }

    int size()
    {
        return  size;
    }

    Object get(int index)
    {
        // 检测index不能越界
        return  array[index];
    }

    boolean isEmpty()
    {
        return 0 == size;
    }
}

    public static void main(String[] args) {
        MyArrayList L1 = new MyArrayList(10);
        L1.add(new Person());
        L1.add(new Person());
        L1.add(new Person());

        // 向下转型:不安全
        //
        Person p = (Person)L1.get(0);
        p.Print();
	}

使用泛型的MyArrayList

class Person{
    public void Print(){
        System.out.println("我是一个好人");
    }
}

// 泛型类
class Book{}
class Person{
    public void Print(){
        System.out.println("我是一个好人");
    }
}
class MyArrayList<E>
{
    public MyArrayList(int capacity){
        array = (E[])new Object[capacity];
        size = 0;
        this.capacity = capacity;
    }

    public void add(E e)
    {
        // 检测容量
        array[size++] = e;
    }

    public int size()
    {
        return  size;
    }

    E get(int index)
    {
        // 检测index不能越界
        return  array[index];
    }

    boolean isEmpty()
    {
        return 0 == size;
    }

    E[] array;
    int capacity;  // 空间的总大小
    int size;      // 空间中存储有效元素的个数
}
    public static void main(String[] args) {
        // L1中只能存储Person类型的对象
        MyArrayList<Person> L1 = new MyArrayList<>(10);
        L1.add(new Person());
        L1.add(new Person());
        // L1.add(new Book());  在编译阶段,发现类型不匹配,编译器报错
        Person p = L1.get(0);
        // Book b = (Book)L1.get(0); // 在编译阶段,发现类型不匹配,强转也不行
        
        // L2中只能存储Book类型的对象
        MyArrayList<Book> L2 = new MyArrayList<>(10);
        L2.add(new Book());
	}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值