自己实现的带泛型ArrayList,泛型arraylist
分享于 点击 14268 次 点评:166
自己实现的带泛型ArrayList,泛型arraylist
public class MyArrayList<T> {
private Object[] arrayList;
private int size;
private int capacity;
public MyArrayList() {
this(10);
}
public MyArrayList(int capacity) {
if(capacity <= 0) {
throw new RuntimeException("必须大于0");
}
this.capacity = capacity;
arrayList = new Object[capacity];
}
public int size() {
return size;
}
public int capacity() {
return capacity;
}
//线性表扩充
public void extendsArrayList() {
if(size >= capacity) {
Object[] newArrayList = new Object[size * 2 + 1];
this.capacity = size * 2 + 1;
for(int i=0; i<size; i++) {
newArrayList[i] = arrayList[i];
}
arrayList = newArrayList;
}
}
//添加
public boolean add(T obj) {
extendsArrayList();
arrayList[size] = obj;
size++;
return true;
}
//指定位置添加
public boolean add(int index,T obj) {
extendsArrayList();
if(index < size && index >=0) {
for(int i=size; i>=index; i--) {
arrayList[i+1] = arrayList[i];
}
arrayList[index] = obj;
size++;
return true;
} else if(index == size){
add(obj);
return true;
} else {
return false;
}
}
//删除
public boolean remove(int index) {
if(index < size) {
for(int i=index; i<size -1; i++) {
arrayList[i] = arrayList[i+1];
}
arrayList[size] = null;
size--;
return true;
} else {
return false;
}
}
//删除
public boolean remove(T obj) {
for(int i=0; i<size; i++) {
if(arrayList[i].equals(obj)) {
remove(i);
break;
}
}
return false;
}
//修改
public boolean set(int index, T obj) {
if(index < size) {
arrayList[index] = obj;
return true;
} else {
return false;
}
}
//获取
public T get(int index) {
if(index <size && index >=0) {
return (T) arrayList[index];
} else {
throw new RuntimeException("数组越界");
}
}
//返回指定元素的位置
public int indexOf(T obj) {
for(int i=0; i<size; i++) {
if(obj.equals(arrayList[i])) {
return i;
}
}
return -1;
}
//返回数据对象
public Object[] toArray() {
return arrayList;
}
//查看是否包含
public boolean contains(T obj) {
for(int i=0; i<size; i++) {
if(arrayList[i].equals(obj)) {
return true;
}
}
return false;
}
}
相关文章
- 暂无相关文章
用户点评