常用方法如下:
名稱 | 作用 |
---|---|
add(Object elem) |
向list中加入參數對象 |
remove(int index) |
移除索引參數對象 |
remove(Object elem) |
移除該參數對象 |
contains(Object elem) |
如果list包含該對象則返回true |
isEmpty() |
如果list中沒有元素則返回true |
indexOf(Object elem) |
返回參數對象的索引或-1 |
size() |
返回list中元素的個數 |
get(int index) |
返回當前索引參數的對象 |
我們注意到,ArrayList沒有內置的sort方法用於排序,那麼要怎麼實現排序功能呢,我們可以使用TreeSet或Collections.sort()方法。
public static void sort(List list)
Collections這個類有個sort()方法,它使用List作爲參數,而ArrayList實現了List接口,所以根據多態機制可以把ArrayList作爲List傳給sort()方法。
例如以下代碼:
import java.util.*;
public class Main{
public static void main(String[] args){
ArrayList<Integer> al = new ArrayList<Integer>();
al.add(5);
al.add(7);
al.add(1);
al.add(5);
Collections.sort(al);
System.out.println(al);
}
}
輸出結果:
[1, 5, 5, 7]