容器类:ArrayList

记事本的例子:

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);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值