Collection集合体系

Collection集合体系

Collection集合是一种单列集合,包含List和Set两类。List常见的有ArrayList和LinkedList,Set常见的有HashSet和TreeSet。
Collection集合常用的方法有:
添加元素:public void add()
移除指定元素:public void remove()
判断集合是否为空:public void isEmpty()
输出元素的个数:public void size()
清空元素:public void clear()

public class CollectionDemo {
    public static void main(String[] args) {
        Collection<String> c = new ArrayList<String>();
        //添加元素
        c.add("hello");
        c.add("world");
        c.add("java");
        System.out.println(c);

        //删除指定元素
        System.out.println(c.remove("world"));

        //判断集合是否为空
        System.out.println(c.isEmpty());

        //得到集合元素个数
        System.out.println(c.size());

        //清除元素
        c.clear();
        System.out.println(c);
    }
}
[hello, world, java]
true
false
2
[]

利用对象迭代器遍历集合元素,首先要创建集合对象并添加元素,然后用iterator方法调出对象迭代器进行遍历。

public static void main(String[] args) {
    Collection<String> c = new ArrayList<String>();//创建集合对象
    //添加对象元素
    c.add("hello");
    c.add("world");
    c.add("java");

    //调出对象迭代器
    Iterator<String> it = c.iterator();
    /*逐个输出对象元素
    System.out.println(it.next());
    System.out.println(it.next());
    System.out.println(it.next());
    System.out.println(it.next());//NoSuchElementException:对象元素不存在
    */

    /*利用if语句判断下个元素是否存在
    if (it.hasNext()){
        System.out.println(it.next());
    }
    if (it.hasNext()){
        System.out.println(it.next());
    }
    if (it.hasNext()){
        System.out.println(it.next());
    }
    if (it.hasNext()){
        System.out.println(it.next());
    }
     */

    //利用while循环判断是否存在下个元素
    while (it.hasNext()){
        System.out.println(it.next());
    }
}
hello
world
java
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值