ArrayList 常用函数功能和代码示例

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.*;

public class ArrayListF{
    public static void main(String[] args) throws Exception{
        // 创建ArrayList
        ArrayList<String> list = new ArrayList<String>(10);

        // 向ArrayList中添加新的元素
        list.add("This");
        list.add("is");
        list.add("my");
        list.add("site");

        // ArrayList的遍历
        for (Iterator iter = list.iterator(); iter.hasNext();) {
            System.out.println("next is: " + iter.next());
        }

        // 获取当前ArrayList的大小
        // size() - number of items
        System.out.println("size of list = " + list.size());

        // 获取当前ArrayList的容量
        // capacity() - number of items it can hold
        Field arrayField = ArrayList.class.getDeclaredField("elementData");
        arrayField.setAccessible(true);
        Object[] internalArray = (Object[])arrayField.get(list);
        System.out.println("capacity of list = " + internalArray.length);

        // 判断ArrayList数组是否为空
        // is_empty()
        System.out.println(list.isEmpty());

        // 根据索引,获取某个元素
        int index = 3;
        System.out.println("the " + index + " element is " + list.get(index));

        // 在某个位置插入某个元素
        index = 3;
        list.add(index, "the insert one");
        for (Iterator iter = list.iterator(); iter.hasNext();) {
            System.out.println("next is: " + iter.next());
        }

        // 将某个位置替换为某个元素
        list.set(index, "set another one");
        for (Iterator iter = list.iterator(); iter.hasNext();) {
            System.out.println("next is: " + iter.next());
        }

        // 删除某个元素
        list.remove("set another one");

        // 判断是否存在某个元素
        System.out.println(list.contains("set another one"));
        System.out.println(list.contains("This"));

        // 清空ArrayList
        list.clear();

        // 判断ArrayList是否是空的
        System.out.println(list.isEmpty());

    }

}
0

Leave a Reply

Your email address will not be published.