线性表
这个比较重要希望看完能理解
代码如下:
十个方法:
package Day07;
import java.util.Arrays;
public class MyArrayList {
public static final int DEFAULT_CAPACITY = 1;
private int size = 0;
private Object[] elements;
/**
*
*/
public MyArrayList() {
this.size = 0;
this.elements = new Object[DEFAULT_CAPACITY];
}
public int getSize() {
return size;
}
public Object[] getElements() {
return elements;
}
public void add(Object o) {
if (size >= elements.length) {
Object[] temp = new Object[elements.length * 2];
for (int i = 0; i < elements.length; i++) {
temp[i] = elements[i];
}
elements = temp;
}
elements[size++] = o;
}
public void add(int index, Object o) {
if (size >= elements.length) {
Object[] temp = new Object[elements.length * 2];
for (int i = 0; i < elements.length; i++) {
temp[i] = elements[i];
}
elements = temp;
}
elements[index] = o;
size++;
}
public void clear() {
for (int i = 0; i < size; i++) {
elements[i] = null;
}
}
public boolean contains(Object o) {
boolean isInArray = false;
for (int i = 0; i < size; i++) {
if (elements[i].equals(o)) {
isInArray = true;
break;
}
}
return isInArray;
}
public Object get(int index) {
return elements[index];
}
public int indexOf(Object o) {
int index = -1;
for (int i = 0; i < size; i++) {
if (elements[i].equals(o)) {
index = i;
break;
}
}
return index;
}
public boolean isEmpty() {
return this.size == 0;
}
public void set(int index, Object o) {
if (index >= 0 && index < size) {
elements[index] = o;
} else {
System.out.println("index out of bound.");
}
}
public int size() {
return this.size;
}
public static void main(String[] args) {
MyArrayList arr1 = new MyArrayList();
arr1.add("abc");
arr1.add("123");
System.out.println(Arrays.toString(arr1.getElements()));
System.out.println(arr1.contains("123"));
System.out.println(arr1.contains("1"));
}
}