集合框架1

集合:
集合是一个容器,数组也是一个容器,但是呢数组的大小是固定的、类型是唯一的因此在某些需求上有限制

集合特点:

	容器大小可变

	可以存储多种数据类型的值【只能是引用数据类型,对基本数据类型而言存储的是其包装类】

	根据集合的存储方式不同,将集合划分两大类:一类是单列集合,另一类是双列集合

	关键词:Collection(单列集合)、Map(双列集合)

单列集合

Collection被称为是单列集合

List							允许重复、有序(输入输出顺序)

Set							不允许重复、无序(不保证输出顺序)

Collection中的方法:

添加:

add(Object object)							   向集合中添加一个元素 	   addAll(Collection collection)			  向集合中添加另一个集合
/**
	 * 添加方法
	 */
	public static void addMethod() {
		// 创建集合对象
		Collection coll = new ArrayList();
		coll.add("hahaha");
		coll.add(123);
		coll.add("小柒");
		System.out.println("coll-->" + coll);

		Collection coll2 = new ArrayList();
		coll2.add("hehe");
		coll2.add(123);
		System.out.println("coll2-->" + coll2);
	}

删除:
remove(Object object) 从集合中移除指定的元素
removeAll(Collection collection) 从集合中移除指定的元素集合

clear() 清空集合中的所有元素

/**
	 * 移除元素
	 */
	public static void removeMethod() {
		// 创建集合对象
		Collection coll = new ArrayList();
		coll.add("hahaha");
		coll.add(123);
		coll.add("小柒");
		System.out.println("移除前的集合:" + coll);

		// 移除单个元素
		coll.remove("haha");
		System.out.println("移除单个元素后的集合:" + coll);

		// 移除指定集合的元素 只要有相同的就移除
		Collection coll2 = new ArrayList();
		coll2.add(123);
		coll2.add("hehe");
		// 交集关系
		coll2.removeAll(coll2);
		System.out.println("移除指定集合后的集合:" + coll);
		System.out.println("coll2中的元素:" + coll2);
		// 清空集合 只是将集合中的元素清除了
		coll.clear();
		System.out.println("清空后的集合:" + coll);
		// 判断集合是否为空 isEmpty()
		System.out.println("是否为空:" + coll.isEmpty());
	}

遍历:

iterator() 遍历集合

/**
	 * 迭代器(遍历)
	 */
	public static void iteratorMethod() {
		Collection coll = new ArrayList();
		coll.add("hahaha");
		coll.add(123);
		coll.add("小柒");

		Iterator it = coll.iterator();
		// 先通过下一个指针去判断是否有下一个元素
		while (it.hasNext()) {
			// 需求:如果是字符串就输出其长度
			Object obj = it.next();
			if (obj instanceof String) {
				String str = (String) obj;
				System.out.println(str);
			}
		}
	}

转换:
toArray()
将集合转换为数组----注意:集合中元素的类型是惟一的

/**
	 * 集合转数组
	 */
	public static void changeArrayMethod() {
		Collection coll = new ArrayList();
		coll.add("hahaha");
		coll.add(123);
		coll.add("小柒");
		// 将集合转化为数组
		Object[] objs = coll.toArray();
		for (int i = 0; i < objs.length; i++) {
			if (objs[i] instanceof String) {
				String str = (String) objs[i];
				System.out.println(str);
			}
		}
	}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值