Java Tutorial/Collections/ArrayList

Материал из Java эксперт
Версия от 05:04, 1 июня 2010; Admin (обсуждение | вклад) (1 версия)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

Содержание

A boolean is being stored and then retrieved from an ArrayList

import java.util.ArrayList;
public class Main {
  public static void main(String... args) {
    ArrayList<Boolean> list = new ArrayList<Boolean>();
    list.add(true);
    boolean flag = list.get(0);
  }
}





Add an element to specified index of ArrayList

import java.util.ArrayList;
public class Main {
  public static void main(String[] args) {
    ArrayList<String> arrayList = new ArrayList<String>();
    arrayList.add("1");
    arrayList.add("2");
    arrayList.add("3");
    arrayList.add(1, "INSERTED");
    for (String str: arrayList)
      System.out.println(str);
  }
}
/*
1
INSERTED
2
3
*/





Adding elements in the middle of a List

import java.util.ArrayList;
import java.util.List;
public class MainClass {
  public static void main(String args[]) throws Exception {
    List list = new ArrayList();
    list.add("A");
    list.add("B");
    list.add("C");
    list.add(1, "G");
    System.out.println(list);
  }
}



[A, G, B, C]


Adding Single Elements

Adding a single element to the list by calling the add() method:



public boolean add(Object element)
public boolean add(int index, Object element)



[A, B, C]


After adding all of the elements, call the trimToSize() method

public void trimToSize()





Append all elements of other Collection to ArrayList

import java.util.ArrayList;
import java.util.Vector;
public class Main {
  public static void main(String[] args) {
    ArrayList<String> arrayList = new ArrayList<String>();
    arrayList.add("1");
    arrayList.add("2");
    arrayList.add("3");
    Vector<String> v = new Vector<String>();
    v.add("4");
    v.add("5");
    // append all elements of Vector to ArrayList
    arrayList.addAll(v);
    for (String str : arrayList)
      System.out.println(str);
  }
}
/*
1
2
3
4
5
*/





ArrayList Class

The ArrayList class is the Collection Framework"s replacement for the Vector class.

The main difference is: ArrayList is not synchronized by default, whereas Vector is. Both maintain their data in an ordered fashion.

Ordered means the elements are held according to the positional index inserted, sorted refers to the comparison of element values for ordering.

The ArrayList and Vector provide quick, random access to elements at a cost of slower insertion and deletion of those elements not at the end of the list.

If you need to frequently add and delete elements from the middle of the list, consider using a LinkedList.


ArrayList implements the empty Serializable interface

If all of the elements of an ArrayList are Serializable, you can then serialize the list to an ObjectOutputStream and later read it back from an ObjectInputStream.



import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Arrays;
import java.util.List;
public class MainClass {
  public static void main(String[] a) throws Exception {
    List list = Arrays.asList(new String[] { "A", "B", "C", "D" });
    FileOutputStream fos = new FileOutputStream("list.ser");
    ObjectOutputStream oos = new ObjectOutputStream(fos);
    oos.writeObject(list);
    oos.close();
    FileInputStream fis = new FileInputStream("list.ser");
    ObjectInputStream ois = new ObjectInputStream(fis);
    List anotherList = (List) ois.readObject();
    ois.close();
    System.out.println(anotherList);
  }
}



[A, B, C, D]


Checking Capacity

The capacity is the number of elements the array list can hold before the internal data structure has to resize.

Use the ensureCapacity() method to check that the internal data structure has enough capacity before adding elements:



public void ensureCapacity(int minimumCapacity)



1


Checking for Equality

The ArrayList class gets its equals() method from the AbstractList class:



public boolean equals(Object o)



false


Checking for Existence: public boolean contains(Object element)

import java.util.Arrays;
import java.util.List;
public class MainClass {
  public static void main(String[] a) {
    List list = Arrays.asList(new String[] { "A", "B", "C", "D" });
    System.out.println(list.contains("C"));
  }
}





Checking for List Containment: public boolean containsAll(Collection c)

import java.util.Arrays;
import java.util.List;
public class MainClass {
  public static void main(String[] a) {
    List list = Arrays.asList(new String[] { "A", "B", "C", "D" });
    List list2 = Arrays.asList(new String[] { "B", "A" });
    System.out.println(list.contains(list2));
  }
}



false


Checking for Position

public int indexOf(Object element)
public int lastIndexOf(Object element)



0


Checking Size: public int size(), public boolean isEmpty()

import java.util.Arrays;
import java.util.List;
public class MainClass {
  public static void main(String[] a) {
    List list = Arrays.asList(new String[] { "A", "B", "C", "D" });
    System.out.println(list.size());
    System.out.println(list.isEmpty());
  }
}



4
false


Convert a List (ArrayList) to an Array with full length array

import java.util.ArrayList;
import java.util.List;
public class Main {
  public static void main(String[] args) {
    List<String> carList = new ArrayList<String>();
    carList.add("A");
    carList.add("B");
    carList.add("C");
    carList.add("D");
    String[] carArray = carList.toArray(new String[0]);
    for (String car : carArray) {
      System.out.println(car);
    }
  }
}
/*
A
B
C
D
*/





Convert a List (ArrayList) to an Array with zero length array

import java.util.ArrayList;
import java.util.List;
public class Main {
  public static void main(String[] args) {
    List<String> carList = new ArrayList<String>();
    carList.add("A");
    carList.add("B");
    carList.add("C");
    carList.add("D");
    String[] carArray = carList.toArray(new String[0]);
    for (String car : carArray) {
      System.out.println(car);
    }
  }
}
/*
A
B
C
D
*/





Copy all elements of ArrayList to an Object Array

import java.util.ArrayList;
public class Main {
  public static void main(String[] args) {
    ArrayList<String> arrayList = new ArrayList<String>();
    arrayList.add("1");
    arrayList.add("2");
    arrayList.add("3");
    arrayList.add("4");
    arrayList.add("5");
    Object[] objArray = arrayList.toArray();
    for (Object obj : objArray)
      System.out.println(obj);
  }
}





Copying and Cloning Lists: public Object clone()

  1. When you call the clone() method of an ArrayList, a shallow copy of the list is created.
  2. The new list refers to the same set of elements as the original.
  3. It does not duplicate those elements.
  4. Since clone() is a method of the ArrayList class and not the List (or Collection) interface, you must call clone() on a reference to the class, not the interface.



import java.util.ArrayList;
import java.util.List;
public class MainClass {
  public static void main(String[] a) {
    List list = new ArrayList();
    list.add("A");
    List list2 = ((List) ((ArrayList) list).clone());
    System.out.println(list);
    System.out.println(list2);
    list.clear();
    System.out.println(list);
    System.out.println(list2);
  }
}



[A]
[A]
[]
[A]


Copying elements out of a list into an array

public Object[] toArray()
public Object[] toArray(Object[] a)



A
B
C
D
A
B
C
D


Creating an ArrayList

  1. For the first two constructors, an empty array list is created.
  2. The initial capacity is ten unless explicitly specified by using the second constructor.



public ArrayList()
public ArrayList (int initialCapacity)



For Sun"s reference implementation, the formula to increase capacity is newCapacity= (oldCapacity * 3)/2 + 1.


Fetching Elements with iterator

public Iterator iterator()
public ListIterator listIterator()
public ListIterator listIterator(int index)



A
B
C
D


Get container with Iterator from ArrayList

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class MainClass {
  public static void main(String[] args) {
    List cats = new ArrayList();
    for (int i = 0; i < 7; i++)
      cats.add(new Cat(i));
    Iterator e = cats.iterator();
    while (e.hasNext())
      ((Cat) e.next()).id();
  }
}
class Cat {
  private int catNumber;
  public Cat(int i) {
    catNumber = i;
  }
  public void id() {
    System.out.println("Cat #" + catNumber);
  }
}
/*
*/



Cat #0
Cat #1
Cat #2
Cat #3
Cat #4
Cat #5
Cat #6


Get Sub List of ArrayList

import java.util.ArrayList;
import java.util.List;
public class Main {
  public static void main(String[] args) {
    ArrayList<String> arrayList = new ArrayList<String>();
    arrayList.add("1");
    arrayList.add("2");
    arrayList.add("3");
    arrayList.add("4");
    arrayList.add("5");
    List lst = arrayList.subList(1, 3);
    for (int i = 0; i < lst.size(); i++)
      System.out.println(lst.get(i));
    // remove one element from sub list
    Object obj = lst.remove(0);
    System.out.println(obj + " is removed");
    for (String str: arrayList)
      System.out.println(str);
  }
}





Getting an Element

The ArrayList class supports retrieval of a single element by index with "public Object get(int index)".



import java.util.ArrayList;
import java.util.List;
public class MainClass {
  public static void main(String args[]) throws Exception {
    List list = new ArrayList();
    list.add("A");
    list.add("B");
    list.add("C");
    System.out.println(list.get(2));
  }
}



C


If an ArrayList contains a given item

import java.util.ArrayList;
import java.util.List;
public class Main {
  public static void main(String[] args) {
    List list = new ArrayList();
    list.add("Item 1");
    list.add("Item 2");
    if (list.contains("Item 1")) {
      System.out.println("True");
    } else {
      System.out.println("False");
    }
  }
}





Insert all elements of other Collection to Specified Index of ArrayList

import java.util.ArrayList;
import java.util.Vector;
public class Main {
  public static void main(String[] args) {
    ArrayList<String> arrayList = new ArrayList<String>();
    arrayList.add("1");
    arrayList.add("2");
    arrayList.add("3");
    Vector<String> v = new Vector<String>();
    v.add("4");
    v.add("5");
    // insert all elements of Vector to ArrayList at index 1
    arrayList.addAll(1, v);
    
    for (String str: arrayList)
      System.out.println(str);
  }
}
/*
1
4
5
2
3
*/





Looping through a Collection object: while loop, iterator, and for each

import java.util.ArrayList;
import java.util.Iterator;
public class Main {
  public static void main(String[] args) {
    ArrayList<String> list = new ArrayList<String>();
    list.add("Monday");
    list.add("Tuesdag");
    list.add("Wednesday");
    list.add("Thursday");
    list.add("Friday");
    list.add("Saturday");
    list.add("Sunday");
    Iterator<String> iterator = null;
    iterator = list.iterator();
    while (iterator.hasNext()) {
      String element = iterator.next();
      System.out.println(element);
    }
    for (iterator = list.iterator(); iterator.hasNext();) {
      String element = iterator.next();
      System.out.println(element);
    }
    for (String element : list) {
      System.out.println(element);
    }
  }
}
/*
Monday
Tuesdag
Wednesday
Thursday
Friday
Saturday
Sunday
Monday
Tuesdag
Wednesday
Thursday
Friday
Saturday
Sunday
Monday
Tuesdag
Wednesday
Thursday
Friday
Saturday
Sunday
*/





Remove duplicate items from an ArrayList

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
public class Main {
  public static void main(String[] argv) {
    List<String> arrayList1 = new ArrayList<String>();
    arrayList1.add("A");
    arrayList1.add("A");
    arrayList1.add("B");
    arrayList1.add("B");
    arrayList1.add("B");
    arrayList1.add("C");
    HashSet<String> hashSet = new HashSet<String>(arrayList1);
    List<String> arrayList2 = new ArrayList<String>(hashSet);
    for (Object item : arrayList2)
      System.out.println(item);
  }
}
/*
A
B
C
*/





Removing All Elements

The simplest removal method, clear(), is the one that clears all of the elements from the list.

You will get an UnsupportedOperationException if the list is read-only.



import java.util.ArrayList;
import java.util.List;
public class MainClass {
  public static void main(String args[]) throws Exception {
    List list = new ArrayList();
    list.add("A");
    list.add("B");
    list.add("C");
    list.clear();
    System.out.println(list);
  }
}





Removing Another Collection(Removing elements): public boolean removeAll(Collection c)

If an element from the passed-in collection is in the list multiple times, all instances are removed.



import java.util.ArrayList;
import java.util.List;
public class MainClass {
  public static void main(String args[]) throws Exception {
    List list = new ArrayList();
    list.add("A");
    list.add("A");
    list.add("B");
    list.add("B");
    list.add("C");
    list.add("C");
    List list2 = new ArrayList();
    list2.add("A");
    list2.add("B");
    list2.add("C");
    list.removeAll(list2);
    System.out.println(list);
  }
}



[]


Removing a Single Element

Use the remove() method to remove a single element:

  1. public boolean remove(Object element)
  2. Removes a single element by checking for equality,
  3. Returns true if the object was found and removed from the list,
  4. Otherwise, false is returned.

If the list contains duplicates, the first element in the list that matches the element will be removed.

If removal is not supported, you"ll get an UnsupportedOperationException.

If the index passed in is outside the valid range of elements, an IndexOutOfBoundsException is thrown.



import java.util.ArrayList;
import java.util.List;
public class MainClass {
  public static void main(String args[]) throws Exception {
    List list = new ArrayList();
    list.add("A");
    list.add("B");
    list.add("C");
    System.out.println(list.remove(0));
    System.out.println(list.remove("B"));
    System.out.println(list);
  }
}



A
true
[C]


Removing Ranges

The removeRange() method is a protected support method used by ArrayList. Unless you subclass ArrayList, you"ll never use it directly:



protected void removeRange(int fromIndex, int toIndex)





Replacing Elements with the set() method: public Object set(int index, Object element)

The object being replaced is returned by the set() method.



import java.util.Arrays;
import java.util.List;
public class MainClass {
  public static void main(String[] a) {
    List list = Arrays.asList(new String[] { "A", "B", "C", "D" });
    list.set(2, "X");
    System.out.println(list);
  }
}



[A, B, X, D]


Search an element of ArrayList with indexOf and lastIndexOf

import java.util.ArrayList;
public class Main {
  public static void main(String[] args) {
    ArrayList<String> arrayList = new ArrayList<String>();
    arrayList.add("2");
    arrayList.add("2");
    arrayList.add("3");
    arrayList.add("4");
    arrayList.add("5");
    arrayList.add("1");
    arrayList.add("2");
    System.out.println(arrayList.contains("2"));
    int index = arrayList.indexOf("4");
    if (index == -1)
      System.out.println("not contain 4");
    else
      System.out.println("4 at index :" + index);
    int lastIndex = arrayList.lastIndexOf("1");
    if (lastIndex == -1)
      System.out.println("not contain 1");
    else
      System.out.println("Last index :"+ lastIndex);
  }
}
/*true
4 at index :3
Last index :5
*/





The final constructor is the copy constructor: creating a new ArrayList from another collection

public ArrayList(Collection col)



[A, B, C, D]


To create a read-only list, use the unmodifiableList() method of the Collections class

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class MainClass {
  public static void main(String args[]) throws Exception {
    List list = new ArrayList();
    list.add("A");
    list.add("B");
    list.add("C");
    list = Collections.unmodifiableList(list);
    list.add(1, "G");
    System.out.println(list);
  }
}



Exception in thread "main" java.lang.UnsupportedOperationException
  at java.util.Collections$UnmodifiableList.add(Collections.java:1160)
  at MainClass.main(MainClass.java:14)