二、创建一个MyArrayList类
public class MyArrayList {
private String[] array = null;
private int size = 0;
private int capacity = 100;
public MyArrayList() {
this.array = new String[capacity];
}
}
一、顺序表实现的功能
(一)、顺序表的扩容
public void add(String elem) {
if (size >= capacity) {
realloc();
}
array[size] = elem;
size++;
}
(二)、顺序表的插入元素
1、顺序表尾部插入
public void add(String elem) {
if (size >= capacity) {
realloc();
}
array[size] = elem;
size++;
}
2、顺序表中间位置插入
public void add(int index, String elem) {
if (index > size || index < 0) {
return;
}
if (size >= capacity) {
realloc();
}
for (int i = size - 1; i >= index; i--) {
array[i + 1] = array[i];
}
array[index] = elem;
size++;
}
(三)、顺序表的删除元素
1、按照元素下标删除
public String remove(int index) {
if (index < 0 || index >= size) {
return null;
}
String result = array[index];
for (int i = index; i < size - 1; i++) {
array[i] = array[i + 1];
}
size--;
return result;
}
2、按照元素的值删除
public boolean remove(String elme) {
int index = 0;
for (; index < size; index++) {
if (array[index].equals(elme)) {
break;
}
if (index >= size) {
return false;
}
}
for (int i = index; i < size - 1; i++) {
array[i] = array[i + 1];
}
size--;
return true;
}
(四)、顺序表的获取元素
public String get(int index) {
if (index < 0 || index >= size) {
throw new MyArrayListIndexOutOfRangeException("下标越界");
}
return array[index];
}
(五)、顺序表根据下标修改元素
public void set(int index, String elem) {
if (index < 0 || index >= size) {
throw new MyArrayListIndexOutOfRangeException("下标越界");
}
array[index] = elem;
}
(六)、顺序表判断元素书否存在
public boolean contains(String elem) {
for (int i = 0; i < size; i++) {
if (array[i].equals(elem)) {
return true;
}
}
return false;
}
(七)、 顺序表查找元素位置
public int index0f(String elem) {
for (int i = 0; i < size; i++) {
if (array[i].equals(elem)) {
return i;
}
}
return -1;
}
(八)、顺序表的打印
public String toString() {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("[");
for (int i = 0; i < size; i++) {
stringBuilder.append(array[i]);
if (i < size - 1) {
stringBuilder.append(",");
}
}
stringBuilder.append("]");
return stringBuilder.toString();
}