您的位置:首页 > 编程语言 > Java开发

JAVA中ArrayList顺序容器

2016-07-17 15:35 295 查看
容器类

ArrayList notes = new ArrayList();

容器类有两个类型:

1.容器的类型

2.元素的类型

package test;
import java.util.ArrayList;
public class NoteBook{
private ArrayList<String> notes = new ArrayList<String>();
public void add(String s){
notes.add(s);
}//向容器中最后添加元素,加的元素从下标0位置开始,与数组下标索引方式相同

public void add(String s,int location){
notes.add(location,s);
}//把元素添加到location下标位置,该位置原有元素向后推1个位置

public void removeNote(int index){
notes.remove(index);//把下标为index位置元素删除并返回
}//删除index下标位置的元素

public int getSize(){
return notes.size();
}//返回容器中元素个数

public String getNote(int index){
return notes.get(index);
}//返回容器中index下标的元素

public String[] list(){
String[] a = new String[notes.size()];
/*
for(int i=0;i<notes.size();i++){
a[i]=notes.get(i);
}
*/
notes.toArray(a);
return a;
}//把容器中的元素放到一个数组中并且返回该数组

public static void main(){
NoteBook  nb = new NoteBook();
nb.add("first");
nb.add("second");
System.out.println(nb.getSize()+nb.getNote(0)+nb.getNote(1));
nb.removeNote(1);
String[] a= nb.list();
for(String s : a){
System.out.println(s);
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java