public class ArrayList<E> extends AbstractList<E>implements List<E>,
Resizable-array implementation of the List interface. Implements all optional list operations, and permits all elements, includingnull. In addition to implementing the List interface, this class provides methods to manipulate the size of the array that is used internally to store the list. (This class is roughly equivalent to Vector, except that it is unsynchronized.)
list接口的实现。
Common ArrayList methods and constructors 常见构造函数和方法
Here are some of the most useful ArrayList methods. Assume these declarations. Note that E
is the notation for the type of an element in a collection. Sun recommends using single upper case letters for generic types.
int i; ArrayList<E> a; E e; Iterator<E> iter; ListIterator<E> liter; E[] earray; Object[] oarray;
如果我们定义了
ArrayList a=new ArrayList() ;那么这个ArrayL可以存放任何类型的数据。
一旦我们指定了某一特定的类型,就只能放这种类型,如:
ArrayList<Integer> a=new ArrayList<Integer>();
如果a.add("xyz")就会报错。
Adding elements to the end of an ArrayList, getting them by index
ArrayList<E> a = new ArrayList<E>(); // Default size. E s; // Declare s to be an object type E. . . . a.add(s); // Adds s to the end of the ArrayList a . . . s = a.get(i); // Assigns ith element from a to s.
To get successive elements from an ArrayList - Four ways
Use either a for
loop with an integer index to get all the elements from an ArrayList, or go over all elements in a ArrayList using an Iterator (forward) or ListIterator (forward / backward).
- foreach loop. This is fast and works for all kinds of lists, but is not entirely flexible (only sequential forward with no deletions, additions, or multiple references). This should be your first choice in programming. Works efficiently with both ArrayList and LinkedList.
ArrayList<String> a = new ArrayList<String>(); . . . for (String s : a) { System.out.println(s); }
for
loop with index. This is fast, but should not be used with a LinkedList. It does allow orders other than sequentially forward by one.for (int i = 0; i < a.size(); i++) { System.out.println(a.get(i)); }
Iterator<E>
- Allows simple forward traversal. Can be used for the largest number of other kinds of data structures.This example uses an Iterator to print all elements (Strings) in an ArrayList. It uses
hasNext()
, which returns true if there are more elements, andnext()
, which returns the next element. Works with both ArrayList and LinkedList.for (Iterator<String> iter = a.iterator(); iter.hasNext(); ) { System.out.println(iter.next()); }
ListIterator<E>
- Allows traversal of the ArrayList, but it is more general than a simple Iterator, allowing inserts and deletes (although both are very slow for an ArrayList). It also allows bidirectional traversal. Works efficiently with both ArrayList and LinkedList.
Sorting
If the data in your ArrayList has a natural sorting order (ie, implements Comparable, as do String, Integer, ...), you can simply call the static Collections.sort()
method. This is a stable, guaranteed n log n sort.
Collections.sort(yourArrayList);
If you want to choose a different sort criterion or your data doesn't implement xxxx, you will have to define a Comparator and pass that to the sort() method.
Collections.sort(yourArrayList, yourComparator);
Check out Collections for other useful utility methods.
下面是一个完整的例子:
import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Iterator; import java.util.List; /** * 老紫竹JAVA提高教程(7)-认识List列表之ArrayList<br> * * @author 老紫竹 JAVA世纪网(java2000.net) * */ public class Lession7 { public static void main(String[] args) { testNormal(); testSpecial(); // 一个最常见的错误 testForProblem(); } public static void testNormal() { // ------------------------------------------------------- // 声明一个列表 // 允许放入任何数据 // ------------------------------------------------------- ArrayList list = new ArrayList(); // 放入整数 // 当然你用 new Integer(1)也可以 list.add(1); // 放入字符串 list.add("abc"); // 放入浮点数 list.add(new Float(1.11)); // add会将数据保存到列表的尾部 showList(list); // 1, abc, 1.11] // 下面我们在列表的头部增加数据 list.add(0, 2); list.add(0, "bcd"); list.add(0, new Double(2.34)); // 列表可以指定插入的位置 // 0 是头部第一个位置,所以数据都逐个放到最前面了 showList(list); // [2.34, bcd, 2, 1, abc, 1.11] // 下面我们插入到我们希望的任何位置 // 当然不能越界,(0 到 list.size()-1)范围内才可以 list.add(1, 3); list.add(4, "xyz"); // 数据被放到了正确的位置 showList(list); // [2.34, 3, bcd, 2, xyz, 1, abc, 1.11] // ------------------------------------------------------- // 我们有了数据,我们来测试读取数据 // ------------------------------------------------------- // 我们可以通过指定索引的位置,来拿到我们希望的数据 System.out.println(list.get(0)); // 2.34 System.out.println(list.get(4)); // xyz // ------------------------------------------------------- // 测试是否存在某个数据 // ------------------------------------------------------- System.out.println(list.contains("xyz")); // true // 测试是否包含一组数据 Collection c = new ArrayList(); c.add(1); c.add(2); System.out.println(list.containsAll(c)); // true c.add(3); c.add(4); // containsAll_1234=false System.out.println(list.containsAll(c)); // false // ------------------------------------------------------- // 查找某个数据所在的索引位置 // 如果不存在,返回-1 // ------------------------------------------------------- System.out.println(list.indexOf(3)); // 1 System.out.println(list.indexOf("xyz")); // 4 System.out.println(list.indexOf("abcd")); // -1 // ------------------------------------------------------- // 测试删除数据 // 请注意, // 如果你使用整数(int)数字,则默认调用的是remove(int index); // 如果你用 long,则会调用 remove(Object obj); // 所以如果你要删除整数,请使用 remove(new Integer(int)); // ------------------------------------------------------- // 删除索引为1的数据 list.remove(1); // 索引为1的数据被干掉了 showList(list); // [2.34, bcd, 2, xyz, 1, abc, 1.11] // 删除数字1 和字符串 abc list.remove(new Integer(1)); list.remove("xyz"); showList(list); // [2.34, bcd, 2, abc, 1.11] // ------------------------------------------------------- // 迭代器的使用 // ------------------------------------------------------- Iterator it = list.iterator(); while (it.hasNext()) { System.out.print(it.next() + " "); // 2.34 bcd 2 abc 1.11 } System.out.println(); // ------------------------------------------------------- // 转化为数组 // ------------------------------------------------------- Object[] objs = list.toArray(); for (Object obj : objs) { System.out.print(obj + " "); // 2.34 bcd 2 abc 1.11 } System.out.println(); } public static void testSpecial() { // ------------------------------------------------------- // 测试重复和null // ------------------------------------------------------- // List<Integer> list = new ArrayList<Integer>(); list.add(123); list.add(456); list.add(123); list.add(456); // 数据允许重复 showList(list); // [123, 456, 123, 456] list.add(null); list.add(789); list.add(null); list.add(999); // 允许放入多个null showList(list); // [123, 456, 123, 456, null, 789, null, 999] // ------------------------------------------------------- // 测试一下查找最后一次出现的位置 // ------------------------------------------------------- System.out.println(list.indexOf(123)); // 0 System.out.println(list.lastIndexOf(123)); // 2 // ------------------------------------------------------- // 转化为数组 // 记得要转化为Inerger. // ------------------------------------------------------- Integer[] nums = (Integer[]) list.toArray(new Integer[0]); // 注意数据里面有null,所以循环变量不要用int 要用Integer for (Integer num : nums) { System.out.print(num + " "); // 123 456 123 456 null 789 null 999 } System.out.println(); } public static void testForProblem() { // 一些朋友在向循环里向列表增加对象的时候 // 经常忘记初始化,造成最终加入的都是同一个对象 List<MyObject> list = new ArrayList<MyObject>(); MyObject obj = new MyObject(); for (int i = 1; i <= 5; i++) { obj.setName("Name" + i); list.add(obj); } // 里面的数据都是最后一个 showList(list); // [Name5, Name5, Name5, Name5, Name5] // 正确的做法 List<MyObject> list2 = new ArrayList<MyObject>(); MyObject obj2 = null; for (int i = 1; i <= 5; i++) { obj2 = new MyObject(); obj2.setName("Name" + i); list2.add(obj2); } // 里面的数据都是最后一个 showList(list2); // [Name1, Name2, Name3, Name4, Name5] } /** * 显示List里面的数据。 * * @param list */ private static void showList(List list) { System.out.println(Arrays.toString(list.toArray())); } } class MyObject { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } /** * 重写toString方法,输出name */ public String toString() { return name; } }
输出:
[1, abc, 1.11] [2.34, bcd, 2, 1, abc, 1.11] [2.34, 3, bcd, 2, xyz, 1, abc, 1.11] 2.34 xyz true true false 1 4 -1 [2.34, bcd, 2, xyz, 1, abc, 1.11] [2.34, bcd, 2, abc, 1.11] 2.34 bcd 2 abc 1.11 2.34 bcd 2 abc 1.11 [123, 456, 123, 456] [123, 456, 123, 456, null, 789, null, 999] 0 2 123 456 123 456 null 789 null 999 [Name5, Name5, Name5, Name5, Name5] [Name1, Name2, Name3, Name4, Name5]
参考:
http://docs.oracle.com/javase/1.5.0/docs/api/index.html?java/util/ArrayList.html
http://www.leepoint.net/notes-java/data/collections/lists/arraylist.html