提供给你思路,这里我只做往数组里加int数字,其实可以做泛型的,如果你想深研究自己去看JDK源码。 我这里只是简单的做数组之间的复制。代码略长:不懂追问!
public class MyList {
private int size;
Object[] object = null;
Object[] temp;
int sequence = 0;
public MyList() {
this(1);
}
public MyList(int size) {
if (size <= 0) {
throw new IllegalArgumentException("长度应大于0");
} else {
this.size = size;
this.object = new Object[this.size];
}
}
// Add, Insert, Delete, Find
public void add(Object obj) {
if (obj == null) {
throw new IllegalArgumentException("添加的对象不应为null");
} else {
if (sequence >= size) {
this.size++;// 这里扩展空间方式随意,可以每次扩展两倍
temp = new Object[this.size];
System.arraycopy(object, 0, temp, 0, object.length);
object = temp;
temp = null;
}
object[sequence] = obj;
sequence++;
}
}
public void insert(int index, Object obj) {
if (index < 0 || obj == null) {
throw new IllegalArgumentException("插入的索引值应不小于0,并且插入的对象不应为null");
} else {
if (index == object.length) {
add(obj);
} else if (index > object.length) {
throw new IllegalArgumentException("数据越界,插入的索引不应不在数组范围内");
}
if (sequence >= size) {
this.size++;
}
temp = new Object[this.size];
System.arraycopy(object, 0, temp, 0, index);//[1,2,3]
temp[index] = obj;
System.arraycopy(object, index, temp, index+1, object.length-index);
object = temp;
temp = null;
sequence++;
}
}
public void delete(int index) {
if (index < 0 || index>this.size) {
throw new IllegalArgumentException("索引应在数组范围内");
} else {
temp = new Object[--this.size];
System.arraycopy(object, 0, temp, 0, index);
System.arraycopy(object, index+1, temp, index, object.length-1-index);
object = temp;
temp = null;
sequence--;
}
}
public Object find(int index) {
if (index < 0 || index > this.size) {
throw new IllegalArgumentException("索引应大于0或不大于集合元素数");
} else {
return object[index];
}
}
public int size() {
return this.size;
}
}
数组是固定长度的,你学过数据结构的话也就知道,不便于插入和删除,如果你要去实现的话,add方法和Insert方法呢就需要向后移动数据,Delete方法向前移动,Fing方法的话就需要一个equals方法去对比查询。如果你不想去移动的话,也可以建立一个临时数组,相当于一个中转站一样。。。
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.border.TitledBorder;
public class ttt {
int arry[];
int temp[];
public ttt()
{
arry = new int[0];
}
public void add(int x)
{
temp = arry;
arry = new int[arry.length + 1];
for (int i = 0; i < temp.length; i++) {
arry[i] = temp[i];
}
arry[arry.length-1] = x;
}
public void delete(int x)
{
temp = arry;
if(arry.length > 1)
arry = new int[arry.length - 1];
else
return;
for (int i = 0,j=0; i < temp.length; i++) {
if(temp[i] == x)
continue;
else{
arry[j] = temp[i];
j++;
}
}
}
public static void main(String[] args) {
ttt t = new ttt();
t.add(2);
t.add(3);
t.delete(2);
System.out.println(t.arry[0]);
}
}
这个好像有困难,list长度不固定,但是数组长度是要固定的,所以add和insert不好弄,除非你定义一个很长的数组