记事本的例子:
import java.util.ArrayList;
class Notebook{
private ArrayList<String> notes=new ArrayList<String>();
public void add(String s) {
notes.add(s);
}
public void add(int location,String s) {
notes.add(location,s);
}
public int getSize() {
return notes.size();
}
public String getNode(int index) {
return notes.get(index);
}
public void remove(int index) {
notes.remove(index);
}
public void set(int index,String s) {
notes.set(index, s);
}
public void clear() {
notes.clear();
}
// public String[] List() {
// String a[]=new String[notes.size()];
// for(int i=0;i<notes.size();i++) {
// a[i]=notes.get(i);
// }
// return a;
// }
//
public String[] List() {
String a[]=new String[notes.size()];
notes.toArray(a);
return a;
}
}
public class Main
{
public static void main(String args[])
{
Notebook a=new Notebook();
a.add("first");
a.add("second");
a.add(1,"third");
String[] x=a.List();
for(String k:x) {
System.out.print(k+" ");
}
a.set(2,"forth");
String[] y=a.List();
for(String k:y) {
System.out.print(k+" ");
}
}
}
运行结果:
first third second
first third forth
ArrayList的操作:
一、添加元素
方法 1):add(value)
功能:在集合末尾追加元素
notes.add(s);
方法 2):add(index,value)
功能:在指定位置index处,插入元素value
notes.add(index,s);
二、获取元素个数
方法:size()
功能:获取ArrayList里元素的个数
notes.size();
三、获取元素
方法:get(index)
功能:获取ArrayList里指定位置index处的元素
notes.get(index);
四、替换元素
方法:set(index,value)
功能:将指定位置index处的元素替换为value
notes.set(index,s);
五、删除元素
方法:1)remove(index)
功能:删除指定位置index处的元素
notes.remove(index)
方法:2)clear()
功能:清除ArrayList里的所有元素
notes.clear();
六、填充元素
方法:toArray(array)
功能:将ArrayList里的所有元素填充进数组array中
notes.toArray(a);