Collection的常用方法

1.add(E e)方法

向集合中添加元素e

语法

Boolean add(E e)

2.addAll(Collection e)方法

向当前集合中添加e集合中所有元素,e集合可以的类型可以是当前类也可以是当前类的子类

语法

Boolean add(Collection<? extends E> e)

1.add(E e)方法

向集合中添加元素e

语法

Boolean add(E e)

3.void clear()方法

把当前集合清空

语法

void clear()

4.迭代器iterator

返回迭代器对象

语法

Iterator iterator();

5.contains方法和remove方法

contains(E e)方法是判断元素是否存在当前集合
remove(E e)方法是删除第一和e一样的元素

语法

Boolean contains(E e)
Boolean remove(E e)

6.containsAll方法和removeAll方法

containsAll(Collection e)方法是判断集合中全部元素是否存在当前集合
removeAll(Collection e)方法是删除当前集合存在e集合是所有元素

语法

Boolean containsAll(Collection<? extends E> e)
Boolean removeAll(Collection<? extends E> e)

7.retainAll方法

retainAll(Collection e)删除当前集合中的元素,如果该集合在e集合中存在就保留

语法

Boolean retainAll(Collection<? extends E> e)

8.toArray()方法和toArray(Object [] o)方法

都是把集合转换为数组,用法不同,看代码

语法

Object [] toArray()
Object [] toArray(Object [] o)

package listAndSet;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;

public class test02 {
	public static void main(String[] args) {
		System.out.println("Collection集合的使用");
		//boolean add(E e)的使用
		Collection<String> str = new ArrayList<String>();
		str.add("你好");
		
		//boolean addAll(E或E的子类 e)的使用
		Collection<String> str2 = new ArrayList<String>();
		str2.add("广西");
		str2.add("你好");
		str2.add("中国");
		str.addAll(str2);
		
		//void clear()的使用
		str2.clear();
		System.out.println(str2);
		
		//迭代器的使用 Iterator<E> iterator()
		Iterator<String> it = str.iterator();
		while (it.hasNext()) {
			System.out.print(it.next() + "\t");
		}
		
		/*
		*boolean contains(E e)和boolean remove(E e)的使用
		*boolean contains(E e)是判断e元素是否存在
		*boolean remove(E e)是删除e在集合中的出现的第一个元素
		*/
		if(str.contains("你好")) {
			str.remove("你好");
		}
		System.out.println(str);
		
		/*
		 * boolean containsAll(Collection<?> e)和boolean removeAll(Collection<?> e)的使用
		 * boolean containsAll(Collection<?> e)是判断是否存在e集合中所有元素
		 * boolean removeAll(Collection<?> e)是把当前集合中出现在e集合里的元素都删除
		 */
		str2.add("广西");
		str2.add("北京");
		str2.add("淮安");
		if (str.containsAll(str2)) {
			str.removeAll(str2);
		}else {
			str.addAll(str2);  //打压不成,咱就拉拢
		}
		System.out.println(str);
		
		//boolean retainsAll(Collection<?> e)求与e的交集,但是可以重复
		Collection<String> str3= new ArrayList<String>();
		str3.add("广西");
		str3.add("淮安");
		str.retainAll(str3);
		System.out.println(str);
		
		//toArray()和toArray(T[] a)和size()使用
		String[] str4 = new String[str.size()];
		str.toArray(str4);   
		//Object[] str5 = str.toArray();
	}
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值