java实现泛型动态数组源码小分享

java实现泛型动态数组源码小分享,第1张

java实现泛型动态数组源码分享 ‍♀️日常小分享,欢迎参考 代码
package com.xmonster.demo2;

import java.util.Arrays;

public class DynamicArray {

    private static final int DEFAULT_CAPACITY = 10;
    private int size;
    private Object[] elementData;
    public DynamicArray(){
        this.elementData = new Object[DEFAULT_CAPACITY];
    }

    private void ensureCapacity(int minCapacity){
        int oldCapacity = elementData.length;
        if(oldCapacity >= minCapacity){
            return;
        }
        int newCapacity = oldCapacity * 2;
        if(newCapacity < minCapacity){
            newCapacity  =minCapacity;
        }
        elementData = Arrays.copyOf(elementData, newCapacity);

    }
    public void add(E e){
        ensureCapacity(size+1);
        elementData[size++]=e;

    }
    public E get(int index){
        return (E)elementData[index];
    }
    public int size(){
        return size;
    }

    public E set(int index, E element){
        E oldValue = get(index);
        elementData[index] = element;
        return oldValue;
    }
    
}
案例
  DynamicArray arr = new DynamicArray<>();
  Random random = new Random();
  int size = 1+random.nextInt(100);
  for (int i = 0; i < size; i++) {
      arr.add(Math.random());
  }
  Double d = arr.get(random.nextInt(size));
  System.out.println(d);

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5719124.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-17
下一篇 2022-12-18

发表评论

登录后才能评论

评论列表(0条)

保存