List集合

List

List作爲Collection接口的子接口,下面是常用的方法

void add(int index,Object element):
boolean addAll(int index,Collection c):
Object get(int index):
int indexOf(Object o):
int lastIndexOf(Object o):
Object remove(int index):
Object set(int index,Object element):
List subList(int fromindex,int toindex):
void replaceAll(UnaryOperator operator):
void sort(Comparator c):

public class ListTest
{
    public static void main(String[] args)
    {
        List books = new ArrayList();
        // 向books集合中添加三個元素
        books.add(new String("輕量級Java EE企業應用實戰"));
        books.add(new String("瘋狂Java講義"));
        books.add(new String("瘋狂Android講義"));
        System.out.println(books);
        // 將新字符串對象插入在第二個位置
        books.add(1 , new String("瘋狂Ajax講義"));
        for (int i = 0 ; i < books.size() ; i++ )
        {
            System.out.println(books.get(i));
        }
        // 刪除第三個元素
        books.remove(2);
        System.out.println(books);
        // 判斷指定元素在List集合中位置:輸出1,表明位於第二位
        System.out.println(books.indexOf(new String("瘋狂Ajax講義"))); //①
        //將第二個元素替換成新的字符串對象
        books.set(1, new String("瘋狂Java講義"));
        System.out.println(books);
        //將books集合的第二個元素(包括)
        //到第三個元素(不包括)截取成子集合
        System.out.println(books.subList(1 , 2));
    }
}
public class ListTest3
{
    public static void main(String[] args)
    {
        List books = new ArrayList();
        // 向books集合中添加4個元素
        books.add(new String("輕量級Java EE企業應用實戰"));
        books.add(new String("瘋狂Java講義"));
        books.add(new String("瘋狂Android講義"));
        books.add(new String("瘋狂iOS講義"));
        // 使用目標類型爲Comparator的Lambda表達式對List集合排序
        books.sort((o1, o2)->((String)o1).length() - ((String)o2).length());
        System.out.println(books);
        // 使用目標類型爲UnaryOperatorLambda表達式來替換集合中所有元素
        // 該Lambda表達式控制使用每個字符串的長度作爲新的集合元素
        books.replaceAll(ele->((String)ele).length());
        System.out.println(books); // 輸出[7, 8, 11, 16]

    }
}
發佈了51 篇原創文章 · 獲贊 23 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章