Java SE Collection

集合

  • 储存对象,长度可变(数组初始化后长度不可变
  • 集合类比数组强大,类似于包装类和基本数据类型

两大接口

Collection

List :可重复放对象、有序
Set :不能重复放对象、按照哈希算法的结果存放
Queue :队列
SortedSet :可对集合排序

Map 映射

SortedMap :可对集合数据排序


collection 接口
add(Object obj)          addAll(Collection c)
clear()               retainAll(Connection c)//delete diffrent from c
contains(Object obj)       containsALl(Collection c)
isEmpty()
Iterator  //return a iterator object
remove(Object obj)        removeAll(Collection c) 
int size()
toArray()//return Object[] 

搞一个带有泛型的小列子

public class Demo{
    public static void main(String[] args)
    {
        Collection <String> c=new ArrayList<>();

        c.add("hello world");
        c.add("java is the best language in the world");

        System.out.println(c);
    }
}

输出:hello world, java is the best language in the world]

提到容器无论是数组还是集合就想搞一件事情,就是存入与取出,遍历算法应运而生。那么collection如何进行遍历呢?

  • 传统的for循环
  • Iterator 迭代器 这是一个对象 Iterator it =arrylist.iterator();接口方法产生的对象
  • for each 增强for循环

    EG:

 public class Demo{
    public static void main(String[] args)
    {
        List<String> list=new ArrayList();
        list.add("hello");
        list.add("world");
        list.add("welcome");
        list.add("thanks");

        System.out.print(list)
        /*遍历输出*/
        //首选迭代器Iterator

        Iterator it =list.iterator();
        while(it.hasNest())
        {
             System.out.print("迭代输出:"+it.next())
        }

        //对对象使用增强for循环
        for(String str:list)//str is a parameter
        {
            System.out.println("fore集合迭代输出:"+str)
        }
    }

            //传统的for方法   for方法内部实例化 Iterator对象
            int=0;
            for(Iterator it=list.iterator();i<list.size();i++)
            {
                System.out.println("输出:"+it.next());
            }
        //利用数组进行遍历输出
        Object[] object=list.toArray();
        for(Object  obj:object)
        {
            System.out.println("输出:"+obj);
        }

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值