}
}
stringBuilder.append("]");
return stringBuilder.toString();
}
// 扩容
private void realloc() {
capacity = 2 * capacity;
String[] newData = new String[capacity];
for (int i = 0; i < data.length; i++) {
newData[i] = data[i];
}
data = newData;
}
// 1.把元素插到顺序表末尾
public void add(String elem) {
if (size >= capacity) {
realloc();
}
data[size] = elem;
size ++;
}
// 时间复杂度:O(N)
// 2.把元素插入到任意中间位置
public void add (int index,String elem) {
if (index < 0 || index > size) {
return;
}
if (size >= capacity) {
realloc();
}
for (int i = size - 1; i >= index; i–) {
data[i + 1] = data[i];
}
data[index] = elem;
size ++;
}
// 3.按照下标位置删除元素
public String remove (int index) {
if (index < 0 || index > size) {
return null;
}
String result = data[index];
for (int i = index; i < size - 1; i++) {
data[i] = data[i + 1];
}
return result;
}
// 4.按照元素的值删除
public boolean remove (String elem) {
int index = 0;
for (; index < size; index++) {
if (data[index].equals(elem)) {
break;
}
}
if (index >= size) {
return false;
}
for (int i = index; i < size; i++) {
data[i] = data[i + 1];
}
size --;
return true;
}
// 5 根据下标获 《一线大厂Java面试题解析+后端开发学习笔记+最新架构讲解视频+实战项目源码讲义》开源 取元素
public String get (int index) {
if (index < 0 || index > size) {
// return null;
// 也可以抛出一个异常
throw new MyArrayListIndexOutOfRangeException("下标越界了! index = " + index);
}
return data[index];
}
// 6 根据下标修改元素
public void set (int index,String el Java开源项目【ali1024.coding.net/public/P7/Java/git】 em) {
if (index < 0 || index > size) {
return;
}
data[index] = elem;
}
// 7 判断元素是否存在
public boolean contains (String elem) {
for (int i = 0; i < size; i++) {
if (data[i].equals(elem)) {
return true;
}
}
return false;
}
// 8 查找元素位置
public int location (String elem) {
for (int i = 0; i < size; i++) {
if (data[i].equals(elem)) {
return i;
}
}
return -1;
}
// 9 查找元素位置,从后往前找
public int locationFromTail (String elem) {
for (int i = size - 1; i > 0; i–) {
if (data[i].equals(elem)) {
return i;
}
}
return -1;
}
public void clear(){
size = 0;
}
public int size(){
return size;
}
public boolean isEmpty(){
return size == 0;
}
// 测试
public static void main(String[] args) {
MyArrayList myArrayList = new MyArrayList();
myArrayList.add(“c”);
myArrayList.add(“c++”);
myArrayList.add(“python”);
最后
我还为大家准备了一套体系化的架构师学习资料包以及BAT面试资料,供大家参考及学习
已经将知识体系整理好(源码,笔记,PPT,学习视频)
码,笔记,PPT,学习视频)
[外链图片转存中…(img-Jc2zFbMm-1650358113316)]
[外链图片转存中…(img-GBRPsIAp-1650358113319)]
[外链图片转存中…(img-yfkf1d94-1650358113321)]