ArrayList是List里面使用率最高的。
package collection.lession7;
import java.util.ArrayList;import java.util.Arrays;import java.util.Collection;import java.util.IteraTor;import java.util.List;/*** 老紫竹JAVA提高教程(7)-认识List列表之ArrayList** @**/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[] bjs = list.toArray(); for (Object obj 呼唤你前往另一个地方,过上另一种生活。