java List集合常用方法

public class Demo {
	public static void main(String[] args) {
		// 创建集合
		List<Integer> list1 = new ArrayList<Integer>();
		List<Integer> list2 = new ArrayList<Integer>();
		List<Integer> list3 = new ArrayList<Integer>();
		System.out.println(list1);// 结果:[]
		System.out.println(list2);// 结果:[]
		System.out.println(list3);// 结果:[]
		// 1、add(E e) - 向列表的尾部添加指定的元素
		list1.add(1);
		list1.add(2);
		System.out.println(list1);// 结果:[1, 2]
		list2.add(3);
		list2.add(4);
		System.out.println(list2);// 结果:[3, 4]
		list3.add(5);
		list3.add(6);
		System.out.println(list3);// 结果:[5, 6]
		// 2、add(int index, E element) - 在列表的指定位置插入指定元素
		list1.add(0, 3);
		System.out.println(list1);// 结果:[3, 1, 2]
		// 3、addAll(Collection c) - 添加指定集合中的所有元素到此列表的结尾
		list1.addAll(list2);
		System.out.println(list1);// 结果:[3, 1, 2, 3, 4]
		// 4、contains(Object o) - 如果列表包含指定的元素,则返回 true
		System.out.println(list1.contains(1));// 结果:true
		System.out.println(list1.contains(6));// 结果:false
		// 5、containsAll(Collection c) - 如果列表包含指定 collection 的所有元素,则返回 true
		System.out.println(list1.containsAll(list2));// 结果:true
		System.out.println(list1.containsAll(list3));// 结果:false
		// 6、equals(Object o) - 比较指定对象与列表是否相等
		System.out.println(list1.equals(list1));// 结果:true
		System.out.println(list1.equals(list2));// 结果:false
		// 7、get(int index) - 返回列表中指定位置的元素
		System.out.println(list1.get(0));// 结果:3
		// 8、indexOf(Object o) - 返回此列表中第一次出现的指定元素的索引,如果不包含该元素,则返回 -1
		System.out.println(list1.indexOf(3));// 结果:0
		// 9、lastIndexOf(Object o) - 返回此列表中最后一次出现的指定元素的索引,如果不包含该元素,则返回 -1
		System.out.println(list1.lastIndexOf(3));// 结果:3
		// 10、isEmpty() - 如果列表不包含元素,则返回 true
		System.out.println(list1.isEmpty());
		// 11、remove(int index) - 移除列表中指定位置的元素
		System.out.println(list1);// 移除前:[3, 1, 2, 3, 4]
		list1.remove(0);
		System.out.println(list1);// 移除后:[1, 2, 3, 4]
		// 12、remove(Object o) - 从此列表中移除第一次出现的指定元素(如果存在)
		System.out.println(list1);// 移除前:[1, 2, 3, 4]
		list1.remove(new Integer(4));
		System.out.println(list1);// 移除后:[1, 2, 3]
		// 13、retainAll(Collection c) - 仅在列表中保留指定指定集合中所包含的元素
		System.out.println(list1);// [1, 2, 3]
		System.out.println(list2);// [3, 4]
		System.out.println(list1.retainAll(list2));
		System.out.println(list1);// 结果:[3]
		// 14、set(int index, E element) - 用指定元素替换列表中指定位置的元素
		list1.set(0, 5);
		System.out.println(list1);// 结果:[5]
		// 15、size() - 返回列表中的元素数
		System.out.println(list1.size());//结果:1
	}
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值