java语言写出一个具有增删功能的自定义数组
时间: 2023-05-27 12:07:57 浏览: 43
public class MyArray {
private int[] array; // 内部数组
private int size; // 数组大小
private int capacity; // 数组容量
public MyArray(int capacity) {
this.array = new int[capacity];
this.size = 0;
this.capacity = capacity;
}
// 获取数组大小
public int getSize() {
return size;
}
// 获取数组容量
public int getCapacity() {
return capacity;
}
// 判断数组是否为空
public boolean isEmpty() {
return size == 0;
}
// 判断数组是否已满
public boolean isFull() {
return size == capacity;
}
// 向数组末尾添加元素
public void add(int element) {
if (isFull()) {
throw new RuntimeException("数组已满,无法添加元素。");
}
array[size++] = element;
}
// 根据索引获取元素
public int get(int index) {
if (index < 0 || index >= size) {
throw new IndexOutOfBoundsException("索引越界。");
}
return array[index];
}
// 修改指定索引的元素
public void set(int index, int element) {
if (index < 0 || index >= size) {
throw new IndexOutOfBoundsException("索引越界。");
}
array[index] = element;
}
// 在指定索引位置插入元素
public void insert(int index, int element) {
if (isFull()) {
throw new RuntimeException("数组已满,无法插入元素。");
}
if (index < 0 || index > size) {
throw new IndexOutOfBoundsException("索引越界。");
}
for (int i = size - 1; i >= index; i--) {
array[i + 1] = array[i];
}
array[index] = element;
size++;
}
// 删除指定索引的元素
public void remove(int index) {
if (isEmpty()) {
throw new RuntimeException("数组为空,无法删除元素。");
}
if (index < 0 || index >= size) {
throw new IndexOutOfBoundsException("索引越界。");
}
for (int i = index; i < size - 1; i++) {
array[i] = array[i + 1];
}
size--;
}
// 查找元素的索引,如果不存在返回-1
public int indexOf(int element) {
for (int i = 0; i < size; i++) {
if (array[i] == element) {
return i;
}
}
return -1;
}
// 清空数组
public void clear() {
size = 0;
}
// 打印数组
public void print() {
StringBuilder sb = new StringBuilder();
sb.append("[");
for (int i = 0; i < size; i++) {
sb.append(array[i]);
if (i < size - 1) {
sb.append(", ");
}
}
sb.append("]");
System.out.println(sb.toString());
}
}