|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 可爱的静静 于 2017-8-13 18:32 编辑
对象容器(顺序容器)ArrayList
例子:记事本
思路:1.先构思记事本有什么功能
2然后把功能用方法表示出来
3补充方法里的方法体
假设一个记事本的功能有:
1 能存储记录
2 不限制能存储的数量
3能查看存进去的每一条记录
4能删除一条记录
5能列出所有的记录
所以方法有:
1 add(String note);
2 grtSize();
3 getNote(intdex);
4 list();
-----------------------构思--------------------------
//先定义好接口
- package UI;
- public class NoteBook {
- public void add(String note){
-
- }
- public int getSize(){
-
- return 0;
- }
- public String getNote(int index){
- return "";
- }
- public void removeNote(int index){
-
- }
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- }
- }
复制代码 ------------------补充接口内容-------------
因为笔记本输入的内容是不断可以增加而且内容是不同类型的
如果用二位数组 并不能 因为不断的放东西
这时候用ArrayList
ArrayList :
返回类型 方法 说明
Bollean add() 列表末尾开始添加 ,从0开始
Int size() 返回列表元素个数
Object get(index) 返回指定位置的元素
Boolean contain(Object o)判断列表中是否存在指定的元素
Boolean remove() 从列表中删除元素
注意:
1索引从0开始
2可以存放不同数据可以不断增加
例子:
- package UI;
- import java.util.ArrayList;
- import java.util.Scanner;
- public class NoteBook {
-
- private ArrayList<String> notes=new ArrayList<String>();
-
- public void add(String s){
- notes.add(s);
-
- }
- public int getSize(){
-
- return notes.size();
- }
- public String getNote(int index){
- return notes.get(index);
- }
- public void removeNote(int index){
- notes.remove(index);
-
- }
- public String [] list(){
- int size=notes.size();
- String[] b=new String[notes.size()];
- for(int i=0; i<size;i++){
- b[i]=notes.get(i);
- }
- return b;
-
- }
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- NoteBook notebook=new NoteBook();
- Scanner in=new Scanner(System.in);
- notebook.add(in.next());
- notebook.add(in.next());
- notebook.add(in.next());
- System.out.println(notebook.getNote(1));
- notebook.removeNote(1);
- String a[]=notebook.list();
- for(int i=0;i<notebook.getSize();i++)
- System.out.println(a[i]);
-
- }
- }
复制代码
容器类型有两种:
容器的类型
元素的类型
|
|