java中list的用法_Java中List的用法

Java中的List是一种集合对象,将所有的对象集中到一起存储。List里面可以放任意的java对象,也可以直接放值,使用方法类似于数组。在使用List之前需要引入头文件java.util.*,例如:

import java.util.*;

public class list{

public static void main(String args[]){

List a = new ArrayLiat();

a.add(1);

System.out.println(a);

a.add(2);

System.oout.pringln(a);

a.remove(0);

System.out.println(a);

}

}

程序的输出结果为:

[1]

[1,2]

[2]

List包括List接口以及List接口的所有实现类,因为List接口实现了Collection接口,所以List接口拥有Collection接口提供的所有常用方法,又因为List是列表类型,所以List接口还提供了一些适合于自身的常用方法。

add(int index,Object obj):

用来向集合的指定索引位置添加对象,其他对象的索引位置相对后移一位,索引位置从0开始

addAll(int,Collection coll):

用来向集合的指定索引位置添加指定集合中的所有对象。

remove(int index):

用来清除集合中指定索引位置的对象

set(int index,Object obj):

用来将集合中指定索引位置的对象修改为指定的对象

get(int index):

用来获得指定索引位置的对象

indexOf(Object obj):

用来获得指定对象的索引位置,当存在多个时,返回第一个的索引位置;当不存在时,返回-1

lastIndexOf(Object obj):

用来获得指定对象的索引位置,当存在多个时,返回最后一个的索引位置;当不存在时,返回-1

lastIterator():

用来获得一个包含所有对象的ListIterator实例

subList(int fromIndex, int toIndex):

通过截取从起始索引位置fromindex到终止索引位置toIndex的对象,重新生成一个List集合并返回

List是个集合接口,只要是集合类接口都会有迭代子(Iterator),利用这个迭代子,就可以对list内存的一组对象进行操作,所有要想操作这个list内存里面的东西,就首先要得到此迭代子的实例:Iterator it = I.iterator();可以理解其为动态数组,传统数组必须定义好数组的个数才可以使用,而容器对象无需定义好数组下标总数。例如:

import java.util.*;

public class ArrayListTest{

public static void main(String dd[]){

//new了一个存储list

List l=new ArrayList();

//因为Collection framework只能存储对象所以new封装类

l.add(new Integer(1));

l.add(new Integer(2));

l.add(new Integer(3));

l.add(new Integer(4));

Iterator it=l.iterator();

//hasNext是取值取的是当前值.他的运算过程是判断下个是否有值如果有继续.

while(it.hasNext()){

//设it.next封装类,调用Integer的intValue方法返回值为int赋给i;

int i=((Integer)it.next()).intValue();

System.out.println("Element in list is :  "+i);

}

}

}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值