ArrayList<String> notes=new ArrayList<String> 容器类型<元素类型> //记事本的例子 //记事本不知道要添加多少条,不能用数组用容器
import java.util.ArrayList; public class Notebook { private ArrayList<String> notes=new ArrayList<String>(); //一个叫notes的成员变量,类型为ArrayList, //用来存放String的ArrayList,叫泛型类是种容器 //notes是对象管理者,因为arraylist是类 public void add(String s) { notes.add(s); } public void add(String s,int location){ notes.add(location,s);//将s加到指定位置 } public int getSize() { return notes.size(); } public String getNote(int index) {//根据Note编号返回对应的note return notes.get(index);//此处下标也由0开始 } public void removeNote(int index) {//据index编号来清除,不需要boolean,当index不对时会抛异常 notes.remove(index); } public String[] list() {//列出所有note String[] a=new String[notes.size()]; //for(int i=0;i<notes.size();i++) { //a[i]=notes.get(i); //} notes.toArray(a); return a; } }