自己實現(xiàn)ArrayList的常用方法
import java.util.List;
import java.util.Set;
import javax.print.attribute.standard.Sides;
public class MyArrayList {
private static final int DEFAULT_SIZE = 10;
//存值的數(shù)組
private Object[] arr;
//數(shù)組中有效元素的個數(shù)
private int size = 0;
//三種初始化構造方法
public MyArrayList() {
arr = new Object[DEFAULT_SIZE];
}
public MyArrayList(int capacity) {
//根據(jù)用戶傳入的長度,定義一個數(shù)組
arr = new Object[capacity];
}
public MyArrayList(List list) {
//保證能保存用戶傳遞進去的數(shù)據(jù),并且多10個空間
arr = new Object[list.size() + DEFAULT_SIZE];
//把老數(shù)組放進新數(shù)組
for (int i = 0; i < list.size(); i++) {
arr[i] = list.get(i);
}
//把新數(shù)組有效長度改成老數(shù)組的有效長度
this.size = list.size();
}
//根據(jù)元素查找位置
public int indexOf(Object o) {
for (int i = 0; i < this.size; i++) {
if (this.arr[i].equals(o)) {
return i;
}
}
return -1;
}
//根據(jù)下標查找元素
public Object get(int index) {
if (index < 0 || index >= this.size) {
return -1;
}
return this.arr[index];
}
//根據(jù)位置刪除元素
public Object remove(int index) {
if (index < 0 || index >= this.size) {
return -1;
}
Object tempObject = this.arr[index];
//this.size - 1 最后一個元素不用管
for (int i = index; i < this.size - 1; i++) {
this.arr[i] = this.arr[i+1];
}
this.size--; //刪除以后個數(shù)減一
return tempObject;
}
//根據(jù)元素刪除元素 (只會刪除出現(xiàn)的第一個)
public boolean remove(Object o) {
//根據(jù)元素找到下標
int index = this.indexOf(o);
if (index == -1) { //沒有找到元素
return false;
}
this.remove(index); //根據(jù)下標刪除元素
return true;
}
//插入元素到固定位置
public Object add(int index,Object element) {
if (index < 0 || index > this.size) {
return -1;
}
if (this.size >= this.arr.length) {
//擴容
Object[] newArr = new Object[this.size + DEFAULT_SIZE];
for (int i = 0; i < size; i++) {
newArr[i] = this.arr[i];
}
this.arr = newArr;
//插入元素
this.add(index, element);
}else {
//插入元素的操作
for (int i = size - 1; i >= index; i--) {
this.arr[i+1] = this.arr[i];
}
this.arr[index] = element;
this.size++;
}
return this.arr[index];
}
//返回數(shù)組的長度
public int size() {
//size 是真實的長度
return this.size;
}
//添加 (插入到數(shù)組的最后)
public boolean add(Object o) {
if (o == null) {
return false;
}
Object object = this.add(size, o);
return true;
}
//用指定的元素替代此列表中指定位置上的元素
public Object set(int index,Object element) {
//判斷index是否越界
if (index < 0 || index >= this.size) {
return -1;
}
//判斷插入的對象是不是為空
if (element == null) {
return null;
}
//設置更新元素
this.arr[index] = element;
return element;
}
//是否包含某個元素 -----很常用
public boolean contains(Object o) {
if (o == null) {
return false;
}
//根據(jù)元素查下標
int index = this.indexOf(o);
if (index >= 0) { //證明可以查找到這個元素
return true;
}
return false;
}
//清空數(shù)組
public void clear() {
this.size = 0;
}
//輸出數(shù)組
@Override
public String toString() {
String string = "[";
for (int i = 0; i < size; i++) {
string+=this.arr[i].toString();
string+=",";
}
//這里是為防止清空數(shù)組以后少一個前括號的問題
if (string.length() >= 2) {
string = string.substring(0, string.length() - 1);
}
string+="]";
return string;
}
}