标签:weight npe gps round bgp pad ddl 删掉 ssr
动态数组代码:
import java.util.Arrays;
public class Array<E> {
private E[] data;
private int size;
//构造函数,传入数组的容量capacity的Array
@SuppressWarnings("unchecked")
public Array(int capacity){
data = (E[]) new Object[capacity];
size = 0;
}
//午参构造函数,默认capacity为10
public Array(){
this(10);
}
//获取数组中元素个数
public int getSize(){
return size;
}
//获取数组的容量
public int getCapacity(){
return data.length;
}
//判断数组是否为空
public boolean isEmpty(){
return size == 0;
}
//在数组下标为index的位置插入一个元素
public void add(int index , E e){
if(index<0||index>size){
throw new IllegalArgumentException("add failed , required index > 0 and index < size");
}
if(size == data.length){
resize(data.length * 2);
}
for(int i=size-1;i>index;i--){
data[i+1] = data[i];
}
data[index] = e;
size++;
}
//向所有元素后添加一个新元素
public void addLast(E e){
add(size , e);
}
//向所有元素前添加一个新元素
public void addFirst(E e){
add(0 , e);
}
//获取index索引位置的元素
public E get(int index){
if(index<0||index>=size){
throw new IllegalArgumentException("get failed , required index > 0 and index < size");
}
return data[index];
}
//修改索引index位置的元素为e
public void set(int index, E e){
if(index<0||index>=size){
throw new IllegalArgumentException("set failed , required index > 0 and index < size");
}
data[index] = e;
}
//判断数组中是否含有元素e
public boolean contains(E e){
for(int i = 0;i<size;i++){
if(e.equals(data[i])){
return true;
}
}
return false;
}
//查找数组中是否含有元素e,返回相应元素的下标
public int find(E e){
for(int i = 0;i<size;i++){
if(e.equals(data[i])){
return i;
}
}
return -1;
}
//从数组中删掉相应下标的元素,返回删掉的元素
public E remove(int index){
if(index<0||index>=size){
throw new IllegalArgumentException("remove failed , required index > 0 and index < size");
}
E ret = data[index];
for(int i=index+1;i<size;i++){
data[i-1] = data[i];
}
size--;
data[size] = null;
if(size == data.length/4 && data.length/2 != 0){
resize(data.length/2);
}
return ret;
}
//从数组中删掉第一个元素,返回删掉的元素
public E removeFirst(){
return remove(0);
}
//从数组中删掉最后一个元素,返回删掉的元素
public E removeLast(){
return remove(size-1);
}
//从数组中删掉元素e
public void removeElement(E e){
int index = find(e);
if(index != -1){
remove(index);
}
}
@Override
public String toString() {
return "Array [data=" + Arrays.toString(data) + ", size=" + size +" Capacity="+data.length+ "]";
}
//重新设置数组容量
private void resize(int newCapacity){
@SuppressWarnings("unchecked")
E[] newData = (E[]) new Object[newCapacity];
for(int i=0;i<size; i++){
newData[i] = data[i];
}
data = newData;
}
}
测试代码:
public static void main(String args[]){
Array<Integer> array = new Array<Integer>(10);
for(int i =0;i<10;i++){
array.add(i, i);
}
System.out.println(array.toString());
array.add(10, 11);
System.out.println(array.toString());
array.remove(5);
System.out.println(array.toString());
}
测试结果:
标签:weight npe gps round bgp pad ddl 删掉 ssr
原文地址:https://www.cnblogs.com/Swen3252/p/9966147.html