标签:java imp package vat ring == buffer update inter
package com.immoc; import java.util.ArrayList; import java.util.List; /** * 实现动态数组 * */ public class Array <E> { private E[]data;; private int size; public Array(int capacity){ data = (E[]) new Object[capacity]; size = 0; } public Array(){ this(10); } public int getSize(){ return size; } public int getCapacity(){ return data.length; } public boolean isEmpty(){ return size==0; } //在数组的最后添加一个元素 public void addList(E e){ add(size, e); } //在数组的最后加入一个元素 public void addFirst(E e){ add(0, e); } //数组中插入一个元素 public void add(int index,E val){ if(index<0||index>size){throw new IllegalArgumentException("传入的参数超过数组的长度");} if(size==data.length){resize(2*getCapacity());} for(int i = size - 1;i >= index;i --){ data[i + 1] = data[i]; } data[index]=val; size++; } //查询某个元素 public E query(int index){ if(index < 0 || index >= size){throw new NullPointerException("null");} return data[index]; } //修改某个元素 public void update(int index, E val){ if(index < 0 || index >= size){throw new NullPointerException("null");} data[index] = val; } //toString方法 @Override public String toString(){ StringBuffer sb = new StringBuffer(); sb.append("数组的长度:"+size+"\t" + "数组的容量:"+data.length + "\n"); sb.append("["); for (int i = 0; i < size; i++) { sb.append(data[i]); if(i !=size-1){ sb.append(","); } } sb.append("]"); return sb.toString(); } //是否包含 public boolean isContain(E val){ for (int i = 0; i < size; i++) { if(val.equals(data[i])){ return true; } } return false; } //删除某个 public E delete( int index ){ if(index < 0 || index >= size){throw new NullPointerException("null");} E ret = data[index]; for (int i = index; i < size; i++) { data[i] = data[i+1]; } size --; if (size < data.length/2){ resize(size); } return ret; } //寻找下标 public int findIndex(E val){ Array a = new Array(); for (int i = 0; i <size; i++) { if (val.equals(data[i])){ return i; } } return -1; } //寻找所有下标 public List findIndexs(E val){ List l = new ArrayList(); for (int i = 0; i <size ; i++) { if(val.equals(data[i])){ l.add(i); } } return l; } //改变容量长度 public void resize(int capacity){ E[] newData = (E[]) new Object[capacity]; for (int i = 0; i <size; i++) { newData[i] = data[i]; } data = newData; } }
标签:java imp package vat ring == buffer update inter
原文地址:https://www.cnblogs.com/zhangzonghua/p/9349957.html