**
P62-P64(记事本的例子、容器):
**
记事本
一、容器类
容器类可以存放任意数量的对象
定义容器类语法
ArrayList < 元素类型 > 对象名 = new ArrayList < 元素类型 >;
二、定义好容器怎么用呢?
ArrayList函数一:将元素放入容器
容器名.add( 添加内容);
ArrayList函数二:将元素插入容器的某个具体位置(其他会自动退后)
容器名.add( 位置,添加内容);
ArrayList函数三:知道容器里面放了多少东西
容器名.size();
ArrayList函数四:获取容器中的某个元素
- 将元素增加进去容器,不是在乱放,是在有顺序的放,类似于数组,下标也是从 0 位置开始放起的。(下标的作用:让我们获取其中的某个元素)
容器名.get(第几个元素);
- 若这个元素超范围了,运行时候运行台会报错
ArrayList函数五:删除容器中某个具体位置上的元素
容器名.remove(要删除元素的位置);
ArrayList函数六:将容器中的所有元素赋给数组
容器名.toArray(数组名);
ArrayList还有许多其他函数…
三、关于ArrayList
- ArrayList 是系统类库当中的一个类,它当中能记录元素,也能自动保持它已经加进去的那些元素的数量
四、记事本例子
package notebook;
import java.util.ArrayList;
public class Notebook {
ArrayList<String> notes=new ArrayList<String>();
public void input(String s) {
notes.add(s);
}
public int getSize() {
return notes.size();
}
public String getNote(int index) {
return notes.get(index);
}
public void removeNote(int loction) {
notes.remove(loction);
}
public String[] list() {
String[] a=new String[notes.size()];
notes.toArray(a);
return a;
}
public static void main(String[] args) {
// TODO 自动生成的方法存根
Notebook book=new Notebook();
book.input("aaaaa");
book.input("bbbbb");
book.input("ccccc");
book.input("ddddd");
System.out.println(book.getSize());
System.out.println(book.getNote(1));
book.removeNote(2);
System.out.println(book.getSize());
System.out.println(book.getNote(1));
String[] a=book.list();
for(String k : a) {
System.out.println(k);
}
}
}