ArrayList用法總結


ArrayList是實現List接口的,底層采用數組實現。

ArrayList 實現了Cloneable接口,即覆蓋了函數clone(),能被克隆。

ArrayList 實現java.io.Serializable接口,這意味着ArrayList支持序列化,能通過序列化去傳輸。

ArrayList 去重

  • 利用HashSet里面的元素不可重復
  • 利用list里面contains方法比較是否存在去重
    第一種方法
        ArrayList<Integer> arrayList = new ArrayList<>();
        arrayList.add(1);
        arrayList.add(2);
        arrayList.add(1);
        arrayList.add(3);
        arrayList.add(2);
        arrayList.add(3);
     
        arrayList = new ArrayList<>(new HashSet<>(arrayList));
     
        for (int i=0;i<arrayList.size();i++){
            printlns("arrayList ["+ i +"] = "+arrayList.get(i));
        }
    運行結果
    arrayList [0] = 1
    arrayList [1] = 2
    arrayList [2] = 3
    第二種方法
    //list:集合,name:元素
    ArrayUtils.contains(list, name)

     

ArrayList的API

// Collection中定義的API
boolean             add(E object)
boolean             addAll(Collection<? extends E> collection)
void                clear()
boolean             contains(Object object)
boolean             containsAll(Collection<?> collection)
boolean             equals(Object object)
int                 hashCode()
boolean             isEmpty()
Iterator<E>         iterator()
boolean             remove(Object object)
boolean             removeAll(Collection<?> collection)
boolean             retainAll(Collection<?> collection)
int                 size()
<T> T[]             toArray(T[] array)
Object[]            toArray()
// AbstractCollection中定義的API
void                add(int location, E object)
boolean             addAll(int location, Collection<? extends E> collection)
E                   get(int location)
int                 indexOf(Object object)
int                 lastIndexOf(Object object)
ListIterator<E>     listIterator(int location)
ListIterator<E>     listIterator()
E                   remove(int location)
E                   set(int location, E object)
List<E>             subList(int start, int end)
// ArrayList新增的API
Object               clone()
void                 ensureCapacity(int minimumCapacity)
void                 trimToSize()
void                 removeRange(int fromIndex, int toIndex)

 JDK6

1、構造函數

     ArrayList提供了三個構造函數:

     ArrayList():默認構造函數,提供初始容量為10的空列表。

     ArrayList(int initialCapacity):構造一個具有指定初始容量的空列表。

     ArrayList(Collection<? extends E> c):構造一個包含指定 collection 的元素的列表,這些元素是按照該 collection 的迭代器返回它們的順序排列的。

2 、新增

      ArrayList提供了add(E e)、add(int index, E element)、addAll(Collection<? extends E> c)、addAll(int index, Collection<? extends E> c)、set(int index, E element)這個五個方法來實現ArrayList增加。

add(E e):將指定的元素添加到此列表的尾部。

add(int index, E element):將指定的元素插入此列表中的指定位置。

 addAll(Collection<? extends E> c):按照指定 collection 的迭代器所返回的元素順序,將該 collection 中的所有元素添加到此列表的尾部。

addAll(int index, Collection<? extends E> c):從指定的位置開始,將指定 collection 中的所有元素插入到此列表中。

 set(int index, E element):用指定的元素替代此列表中指定位置上的元素。

3、刪除

      ArrayList提供了remove(int index)、remove(Object o)、removeRange(int fromIndex, int toIndex)、removeAll()四個方法進行元素的刪除。

remove(int index):移除此列表中指定位置上的元素。

remove(Object o):移除此列表中首次出現的指定元素(如果存在)。

removeRange(int fromIndex, int toIndex):移除列表中索引在 fromIndex(包括)和 toIndex(不包括)之間的所有元素。

removeAll():是繼承自AbstractCollection的方法,ArrayList本身並沒有提供實現。

對JAVA集合進行遍歷刪除時務必要用迭代器

Iterator<String> iter = list.iterator();
while (iter.hasNext()) {
  String item = iter.next();
  if (item.equals("aa")) {
    iter.remove();
  }
}

需要注意使用迭代器的remove()方法。

3、修改

     set(int index, E element) :set(1, "b") 設置第2個元素為b。

4、查找

查找元素有Contains()、IndexOf()、LastIndexOf()3中方法

 

al.Contains(object obj);//查找數組中是否有obj元素,存在返回true;

 

IndexOf()有兩個重載方法 起用法如下:

 

1)、al.IndexOf(object obj);//從0開始查找obj元素,只第一個obj元素,並返回起在數組中的位置,如果不存在,返回-1;

 

2)、al.IndexOf(object obj,int startIndex); //從startIndex開始查找obj元素,只第一個obj元素,並返回起在數組中的位置,

 

3)、al.IndexOf(object obj,int startIndex,int count); 從startIndex開始想后查找count個元素,如果存在obj元素,則返回其在數組中的位置

 

al.LastIndexOf()方法與IndexOf()用法相同,它也有兩個重載,其不同的是,LastIndexOf(obj)是查找要obj最后出現的位置

      ArrayList提供了get(int index)用讀取ArrayList中的元素。由於ArrayList是動態數組,所以我們完全可以根據下標來獲取ArrayList中的元素,而且速度還比較快,故ArrayList長於隨機訪問。

contains(Object o):此集合中是否包含某一個元素。

ArrayList支持3種遍歷方式

(01) 第一種,通過迭代器遍歷。即通過Iterator去遍歷。

Integer value = null;
Iterator iter = list.iterator();
while (iter.hasNext()) {
    value = (Integer)iter.next();
}

(02) 第二種,隨機訪問,通過索引值去遍歷。
由於ArrayList實現了RandomAccess接口,它支持通過索引值去隨機訪問元素。

Integer value = null;
int size = list.size();
for (int i=0; i<size; i++) {
    value = (Integer)list.get(i);        
}

(03) 第三種,for循環遍歷。如下:

Integer value = null;
for (Integer integ:list) {
    value = integ;
}

遍歷ArrayList時,使用隨機訪問(即,通過索引序號訪問)效率最高,而使用迭代器的效率最低!

// 將ArrayList轉換為數組
String[] arr = (String[])list.toArray(new String[0]);
for (String str:arr)
System.out.println("str: "+ str);

// 清空ArrayList
list.clear();
// 判斷ArrayList是否為空
System.out.println("ArrayList is empty: "+ list.isEmpty());

 

/**
* 無序集合轉換為有序列表
*
* @param set
* @return
*/

public static List<String> setSortToList(Set<String> set) {
List<String> setList = new ArrayList<String>(set);
Collections.sort(setList, new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
return o1.compareTo(o2);
}
});
return setList;
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM