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; } }
DynamicArrayarr = 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);
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)