Java实现数据结构数组的添加add、插入insert、删除delete操作
程序员文章站
2022-02-05 19:27:41
...
package com1;
/**
* @author yangxin_ryan
* Java使用数组实现数组的
* add(ele)
* insert(ele, index)
* delete(index)
* 三个函数功能
*/
public class Demo1 {
private Object[] elements;
public Demo1(){
elements = new Object[0];
}
/**
* 在数组末尾添加元素
* @param element
*/
public void add(Object element) {
Object[] newArr = new Object[elements.length + 1];
System.arraycopy(elements, 0, newArr, 0, elements.length);
newArr[elements.length] = element;
elements = newArr;
}
/**
* 在index位置添加元素
* @param element
* @param index
*/
public void insert(Object element, int index) {
Object[] newArr = new Object[elements.length + 1];
System.arraycopy(elements, 0, newArr, 0, index);
newArr[index] = element;
System.arraycopy(elements, index, newArr, index + 1, elements.length - index);
elements = newArr;
}
/**
* 删除指定位置的元素
* @param index
*/
public void delete(int index) {
if (index < 0 || index > elements.length - 1) {
throw new RuntimeException("数据越界");
}
Object[] newArr = new Object[elements.length - 1];
System.arraycopy(elements, 0, newArr, 0, index);
System.arraycopy(elements, index, newArr, index, elements.length - index - 1);
elements = newArr;
}
public static void main(String[] args) {
Demo1 demo1 = new Demo1();
demo1.add(10);
for (Object obj: demo1.elements) {
System.out.println(obj);
}
System.out.println("----------------");
demo1.insert(11, 1);
for (Object obj: demo1.elements) {
System.out.println(obj);
}
System.out.println("----------------");
demo1.delete(1);
for (Object obj: demo1.elements) {
System.out.println(obj);
}
}
}