- //以1为基准
- public class MyVector
- {
- private Object[] elements;
- private int size;
- private int capacityIncrement;//增长的速度
- public MyVector()
- {
- elements = new Object[10];
- }
- public MyVector(Object[] elements)
- {
- this.elements = elements;
- size = elements.length;
- }
- public MyVector(int initalCapacity)
- {
- elements = new Object[initalCapacity];
- }
- public MyVector(int initalCapacity, int capacityIncrement)
- {
- elements = new Object[initalCapacity];
- this.capacityIncrement = capacityIncrement;
- }
- public void add(Object element)
- {
- if(size >= elements.length)
- elements = increaseElements();
- elements[size++] = element;
- }
- public void add(int index, Object element)
- {
- if(0 == size)
- throw new ArrayIndexOutOfBoundsException("the array is null");
- if(index > size+1 || index <1)
- throw new ArrayIndexOutOfBoundsException("out of range");
- if(size >= elements.length)
- elements = increaseElements();
- // System.arraycopy(elements, index-1, elements, index, size-index+1);//System.arraycopy()适合于大数组,调用次数少
- for(int i = size; i >= index; i--)
- elements[i] = elements[i-1];
- elements[index-1] = element;
- size++;
- }
- public void delete() {elements[--size] = null;}
- public void delete(int index)
- {
- if(0 == size)
- throw new ArrayIndexOutOfBoundsException("the array is null");
- if(index > size || index <1)
- throw new ArrayIndexOutOfBoundsException("out of range");
- // System.arraycopy(elements, index, elements, index-1, size-index);
- for(int i = index-1; i < size-1; i++)
- elements[i] = elements[i+1];
- elements[--size] = null;
- }
- public void deleteAll()
- {
- for(int i = 0; i < size; i++)
- elements[i] = null;
- size = 0;
- }
- public Object elementAt(int index) {return elements[index-1];}
- public int getSize() {return size;}
- private Object[] increaseElements()//增长元素的数组
- {
- Object[] increased = new Object[capacityIncrement == 0 ? size*2 : size+capacityIncrement];
- // System.arraycopy(elements, 0, increased, 0, size);
- for(int i = 0; i < size; i++)
- increased[i] = elements[i];
- return increased;
- }
- public static void main(String[] args)
- {
- MyVector mv = new MyVector(10, 2);
- int i;
- for(i = 0; i < 10; i++)
- mv.add(i);
- mv.add(10);
- mv.add(5, 13);
- mv.add(1, 17);
- mv.delete();
- mv.delete(3);
- mv.delete(5);
- for(i = 1; i <= mv.getSize(); i++)
- System.out.print(mv.elementAt(i) + " ");
- System.out.println();
- System.out.println("Vector.size: " + mv.getSize());
- System.out.println("Vector.length: " + mv.elements.length);
- }
- }
自己实现的动态数组(java.util.Vector)
最新推荐文章于 2022-12-31 19:29:18 发布