package utils;
public class MyArrayList<T> {
private static final int DEFAULT_CAPACITY = 50;
private int theSize;
private Object[] theItems;
public MyArrayList() {
clear();
}
public void clear() {
theSize = 0;
ensureCapacity(DEFAULT_CAPACITY);
}
public int size() {
return theSize;
}
public boolean isEmpty() {
return size() == 0;
}
public void trimToSize() {
ensureCapacity(size());
}
public T get(int idx) {
if (idx < 0 || idx >= size())
return null;// should throw exception
return (T)theItems[idx];
}
public T get(T x) {
for (int i = 0; i < size(); ++i) {
if (theItems[i].equals(x)) {
return (T)theItems[i];
}
}
return null;
}
public int indexOf(T x) {
for (int i = 0; i < size(); ++i) {
if (theItems[i].equals(x)) {
return i;
}
}
return -1;
}
public T set(int idx, T newVal) {
if (idx < 0 || idx >= size())
return null;
T old = (T)theItems[idx];
theItems[idx] = newVal;
return old;
}
public void ensureCapacity(int newCapacity) {
if (newCapacity < theSize)
return;
Object[] old = theItems;
theItems = new Object[newCapacity];
for (int i = 0; i < size(); ++i)
theItems[i] = old[i];
}
public boolean add(T x) {
add(size(), x);
return true;
}
public void add(int idx, T x) {
if (theItems.length == size())
ensureCapacity(size() * 2 + 1);
for (int i = theSize; i > idx; i--)
theItems[i] = theItems[i - 1];
theItems[idx] = x;
theSize++;
}
public T remove(int idx) {
T removedItem = (T)theItems[idx];
for (int i = idx; i < size() - 1; ++i)
theItems[i] = theItems[i+1];
theItems[size() - 1] = null;
theSize--;
return removedItem;
}
public T remove(T x) {
for (int i = 0; i < size(); ++i) {
if (theItems[i].equals(x)) {
return remove(i);
}
}
return null;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] a = new int[] {2, 8, 3, 4, 9, 10};
MyArrayList<Integer> list = new MyArrayList<Integer>();
for (int i : a) {
list.add(i);
}
for (int i = 0; i < list.size(); ++i) {
System.out.print(list.get(i) +" ");
}
System.out.println();
System.out.println(list.remove((Integer)2));
System.out.println(list.remove((Integer)10));
System.out.println(list.remove((Integer)3));
System.out.println(list.add((Integer)3));
for (int i = 0; i < list.size(); ++i) {
System.out.print(list.get(i) +" ");
}
}
}
为算法考试做准备--ArrayList实现
最新推荐文章于 2022-10-05 10:52:17 发布