java初学之arrayList

来源:互联网 发布:svm算法步骤 编辑:程序博客网 时间:2024/05/17 23:25

arrayList

System.Collection.ArrayList类是一个特殊的数组。通过添加和删除元素,实现动态的改变数组的长度。

System.Collection.ArrayList is a special array which can change the length of the array dynamically by adding or deleting elements.

一. 新建一个arrayList

I. Establishing

ArrayList alist = new ArrayList();

或or

ArrayList<Integer> aList = new ArrayList<Integer>();

二. 添加元素

II. Adding new elements

1. 将对象添加到arraylist的结尾处 add elements into the end side of an arraylist

aList.add("a");

aList.add("b");

//the result is ab

2.将元素插入到指定索引处 add elements into a specified index

aList.Insert(0,"aa");

//the result is aaab.

3.inset elements from another arraylist into a specified index

aList.InserRange(2, aList2);

III. removing existed elements

1. remove the first matched elements from a specific arraylist

aList.Remove("a");

2. remove an element from a specified index

aList.RemoveAt(0);

3. remove elements from a specified index range

aList.RemoveRange(1, 3);

4. remove all the elements

aList.clear();

IV. sorting

V. searching

VI. Others

VII. 4 ways for tranversal of arrayLists

package com.test;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class ArrayListDemo {
    public static void main(String args[]){
        List<String> list = new ArrayList<String>();
        list.add("luojiahui");
        list.add("luojiafeng");

        //方法1
        Iterator it1 = list.iterator();
        while(it1.hasNext()){
            System.out.println(it1.next());
        }

        //方法2
        for(Iterator it2 = list.iterator();it2.hasNext();){
             System.out.println(it2.next());
        }

        //方法3
        for(String tmp:list){
            System.out.println(tmp);
        }

        //方法4
        for(int i = 0;i < list.size(); i ++){
            System.out.println(list.get(i));
        }

    }
}


0 0