java arraylist 引用_Java ArrayList 使用

public class ArrayList extends AbstractListimplements List,

Resizable-array implementation of theListinterface. Implements all optional list operations, and permits all elements, includingnull. In addition to implementing theListinterface, this class provides methods to manipulate the size of the array that is used internally to store the list. (This class is roughly equivalent toVector, 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 a;

E e;

Iterator iter;

ListIterator liter;

E[] earray;

Object[] oarray;

如果我们定义了

ArrayList a=new ArrayList() ;那么这个ArrayL可以存放任何类型的数据。

一旦我们指定了某一特定的类型,就只能放这种类型,如:

ArrayList a=new ArrayList();

如果a.add("xyz")就会报错。

Adding elements to the end of an ArrayList, getting them by index

ArrayList a = new ArrayList(); //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 a = new ArrayList();

. . .

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 - 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, and next(), which returns the next element. Works with both ArrayList and LinkedList.

for (Iterator iter = a.iterator(); iter.hasNext(); ) {

System.out.println(iter.next());

}

ListIterator - 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.

下面是一个完整的例子:

importjava.util.ArrayList;importjava.util.Arrays;importjava.util.Collection;importjava.util.Iterator;importjava.util.List;/*** 老紫竹JAVA提高教程(7)-认识List列表之ArrayList

*

*@author老紫竹 JAVA世纪网(java2000.net)

**/

public classLession7 {public static voidmain(String[] args) {

testNormal();

testSpecial();//一个最常见的错误

testForProblem();

}public static voidtestNormal() {//-------------------------------------------------------//声明一个列表//允许放入任何数据//-------------------------------------------------------

ArrayList list = newArrayList();//放入整数//当然你用 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 = newArrayList();

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 voidtestSpecial() {//-------------------------------------------------------//测试重复和null//-------------------------------------------------------//  List list = new ArrayList();

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 voidtestForProblem() {//一些朋友在向循环里向列表增加对象的时候//经常忘记初始化,造成最终加入的都是同一个对象

List list = new ArrayList();

MyObject obj= newMyObject();for (int i = 1; i <= 5; i++) {

obj.setName("Name" +i);

list.add(obj);

}//里面的数据都是最后一个

showList(list); //[Name5, Name5, Name5, Name5, Name5]//正确的做法

List list2 = new ArrayList();

MyObject obj2= null;for (int i = 1; i <= 5; i++) {

obj2= newMyObject();

obj2.setName("Name" +i);

list2.add(obj2);

}//里面的数据都是最后一个

showList(list2); //[Name1, Name2, Name3, Name4, Name5]

}/*** 显示List里面的数据。

*

*@paramlist*/

private static voidshowList(List list) {

System.out.println(Arrays.toString(list.toArray()));

}

}classMyObject {privateString name;publicString getName() {returnname;

}public voidsetName(String name) {this.name =name;

}/*** 重写toString方法,输出name*/

publicString toString() {returnname;

}

}

输出:

[1, abc, 1.11]

[2.34, bcd, 2, 1, abc, 1.11]

[2.34, 3, bcd, 2, xyz, 1, abc, 1.11]2.34xyztrue

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]

参考:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值