数组的增删改查
程序员文章站
2024-02-21 10:28:34
...
import java.util.Arrays;
public class MyArray {
private int[] elements;
public MyArray() {
elements = new int[0];
}
//数组长度
public int size() {
return elements.length;
}
//末尾添加元素
public void add(int element) {
int[] newArray = new int[elements.length+1];
for(int i=0;i<elements.length;i++) {
newArray[i] = elements[i];
}
newArray[elements.length] = element;
elements = newArray;
//System.out.println(elements.toString());
}
//删除元素
public void delete(int index) {
if(index<0 || index>elements.length-1) {
throw new RuntimeException("下标越界");
}
int[] tempArray = new int[elements.length-1];
for(int i=0;i<tempArray.length;i++) {
if(i<index) {
tempArray[i] = elements[i];
}else {
tempArray[i] = elements[i+1];
}
}
elements = tempArray;
//System.out.println(elements.toString());
}
//获取某个元素
public int get(int index) {
return elements[index];
}
public void insert(int index,int target) {
int[] newOne = new int[elements.length+1];
for(int i=0;i<elements.length;i++) {
if(i<index) {
newOne[i] = elements[i];
}else {
newOne[i+1] = elements[i];
}
}
newOne[index] = target;
elements = newOne;
}
public void show() {
System.out.println(Arrays.toString(elements));
}
}
public class ArrayFindIndex {
public static void main(String[] args) {
int[] arr = {1,2,5,2,7,23,98,3};
int target = 5;
int index = -1;
for(int i=0;i<arr.length;i++) {
if(arr[i] == target) {
index = i;
break;
}
}
System.out.println(index);
}
}
public class MyArrayTest {
public static void main(String[] args) {
MyArray m = new MyArray();
int length = m.size();
m.show();
m.add(90);
m.add(80);
m.add(12);
m.add(13);
m.add(14);
m.add(15);
m.show();
m.delete(0);
//System.out.println(m.size());
m.show();
//System.out.println(m.get(1));
System.out.println("*********************");
m.insert(2, 100);
m.show();
}
}
上一篇: spf13-vim 介绍及常用快捷键