Java中的集合:Collection接口的子接口 List 中的常用的方法

Collection接口的 子接口 List接口

在这里插入图片描述

List接口中的常用的方法:(除了Collection中的方法之外的List中的方法)

  • void add(int index, Object ele) 在index的位置插入ele元素

  • Boolean addAll(int index, Collection ele) 在index的位置插入集合ele

  • Object get(int index) 获取指定位置上的元素

  • int indexOf(Object obj) 返回在当前集合中obj首次出现的位置

  • int lastIndexOf(Object obj) 返回在当前集合中obj末次出现的位置-

  • Object remove(int index) 移除指定位置上的元素,并返回此元素

  • Object set(int index,Object obj) 设置指定位置上的元素为obj(类似于替换)

  • List subList(int fromIndex,int toIndex) 返回该集合从fromIndex到toIndex位置上的子集合(左闭右开)

常用方法:


  • add(Object o)


  • 1.remove(int index)
    2.remove(Object o)


  • set(int index,Object obj)


  • get(int index)

  • 插入
    add(int index, Object ele)

  • 长度
    size()

  • 遍历
    1.Iterator迭代器
    2.foreach

代码举例:

import java.util.ArrayList;

public class ListTest {
	public static void main(String[] args) {
		ArrayList arrayList = new ArrayList();
		arrayList.add(123);
		arrayList.add("你好");
		arrayList.add(456);
		System.out.println(arrayList+"\n");
		
		arrayList.add(1, 456);
		System.out.println("指定位置插入456后:"+arrayList+"\n");
		
		System.out.println("获取index=0的位置上的元素:"+arrayList.get(0)+"\n");
		
		System.out.println("456首次出现的索引:"+arrayList.indexOf(456)+"\n");

		System.out.println("456最后一次出现的索引:"+arrayList.lastIndexOf(456)+"\n");
		
		arrayList.remove(3);
		System.out.println("移除index=3的元素后的集合"+arrayList+"\n");
		
		arrayList.set(0, "hello,world");
		System.out.println("将index=0的元素设置成hello,world后的集合"+arrayList+"\n");
		
		System.out.println("返回集合索引值为[1,3)上的内容:"+arrayList.subList(1, 3));
		
	}
}

在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值