Collection集合 Iterator迭代器 泛型

集合和数组的基本区别

  1. 数组的长度是固定的。
  2. 集合的长度是可变的 数组存储的是同一类型的元素,可以存储基本数据类型值。集合存储的都是对象。

在这里插入图片描述
Collection的一些共性方法:
Collection是所有单列集合的父接口,因此在Collection中定义了单列集合(List和Set)通用的一些方法,
这些方法可用于操作所有的单列集合。方法如下:

    * `public boolean add(E e)`:  把给定的对象添加到当前集合中 。
    * `public void clear()` :清空集合中所有的元素。
    * `public boolean remove(E e)`: 把给定的对象在当前集合中删除。
    * `public boolean contains(E e)`: 判断当前集合中是否包含给定的对象。
    * `public boolean isEmpty()`: 判断当前集合是否为空。
    * `public int size()`: 返回集合中元素的个数。
    * `public Object[] toArray()`: 把集合中的元素,存储到数组中。

例:

import java.util.ArrayList;
import java.util.Collection;

public class Demo01 {
   

    public static void main(String[] args) {
   
   public boolean add(E e)`:  把给定的对象添加到当前集合中
	返回值是一个bollean值,一般都返回true,所以可以不用接收
        Collection coll = new ArrayList();
        coll.add("Hello");
        coll.add("World");
        coll.add("W");
        coll.add("R");
        coll.add("Z");
        System.out.println(coll);//[Hello, World, W, R, Z]

        public void clear()` :清空集合中所有的元素。但不删除集合,集合还存在
        coll.clear();
        System.out.println(coll);//[]

        public boolean remove(E e)`: 把给定的对象在当前集合中删除

        boolean result = coll.remove("Hello");
        System.out.println(result);//true
        System.out.println(coll);//[World, W, R, Z]

        public boolean contains(E e)`: 判断当前集合中是否包含给定的对象
				返回值是一个boolean值,集合中存在该元素则为true
									   集合中不存在该元素则为false
        boolean result = coll.contains("W");
        System.out.println(result);//true
        System.out.println(coll);//[Hello, World, W, R, Z]

        public boolean isEmpty()`: 判断当前集合是否为空。

        System.out.println(coll.isEmpty());//false

       public int size()`: 返回集合中元素的个数。
        System.out.println(coll.size());//5

        public Object[] toArray()`: 把集合中的元素,存储到数组中。
        Object[] arr = coll.toArray();
        for(int i =0; i<=arr.length; i++){
   
            System.out.println(arr[i]);
        }
    }
}

Iterator迭代器
java.util.Iterator接口:迭代器(对集合进行遍历)
有两个常用方法

  1. boolean hasNext() 如果仍有元素可以迭代,则返回true
    判断集合中还有没

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值