从头认识java-15.2 Collection的常用方法(1)

这一章节我们来介绍一下Collection的常用方法。

我们下面以ArrayList为例。

package com.ray.ch14;

import java.util.ArrayList;
import java.util.Iterator;

public class Test {
	public static void main(String[] args) {
		ArrayList<Integer> rtnList = new ArrayList<Integer>();
		rtnList.add(1);// add方法

		ArrayList<Integer> tempList = new ArrayList<Integer>();
		tempList.add(2);

		rtnList.addAll(tempList);// addAll方法

		System.out.println(rtnList.contains(1));// contains方法

		System.out.println(rtnList.containsAll(tempList));// containsAll方法

		for (Iterator<Integer> iterator = tempList.iterator(); iterator
				.hasNext();) {// Iterator迭代器
			Integer item = (Integer) iterator.next();
			System.out.println(item);
		}

		System.out.println(rtnList.size());// size方法

		rtnList.retainAll(tempList);// retainAll方法

		rtnList.add(1);// add方法
		rtnList.remove(1);// remove方法

		rtnList.removeAll(tempList);// removeAll方法

	}
}


输出:

true
true
2
2

 

Collection的常用操作

方法

意义

boolean add(E e)

添加指定的元素

boolean addAll(Collection<? extends E> c)

将指定collection 中的所有元素都添加到新的collection 中

void clear()

移除所有元素

boolean contains(Object o)

检测是否包含指定的元素,如果真返回true,反之返回false

boolean containsAll(Collection<?> c)

检测是否包含某Collection的所有元素,如果真返回true,反之返回false

boolean equals(Object o)

对比指定的对象

int hashCode()

返回哈希码值

boolean isEmpty()

是否为空

Iterator<E> iterator()

迭代器

boolean remove(Object o)

移除对象

boolean removeAll(Collection<?> c)

移除某Collection的所有元素

boolean retainAll(Collection<?> c)

只保留两个Collection 的交集

Object[] toArray()

返回包含此 collection 中所有元素的数组

<T> T[]toArray(T[] a)

返回包含此 collection 中所有元素的数组;返回数组的运行时类型与指定数组的运行时类型相同

 

 

总结:这一章节主要介绍Collection的常用方法。

 

这一章节就到这里,谢谢。

-----------------------------------

目录

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值