container Holding Your Objects

来源:互联网 发布:淘宝怎么查看买家信用 编辑:程序博客网 时间:2024/05/29 11:47

一 、简单介绍:容器(袋子)

      优点:1、不需要担心袋子(container)大小问题,有多少东西放多少。

               2、东西的类型也不限制,什么东西都可以往里扔。 

              3、如果你想容器放规定的东西,用Generis去限制 ArrayList<Apple> .

              4、对于所有子类,都属于父类这一类型。

 放东西:add()

              insert()

 取东西:get(),

 扔东西:remove()

              clear():袋子清空

 替代:set()

 大小:size(),

二、区别

  1、Collection(袋子).取、查询东西时用一个号i,即号和对象关连

      1.1  a List:放进去东西,不希望别人去移来移去,保持原样。

      1.2  a Set:袋子里的东西不能重复。

      1.3  a Queue:排队一样,排的前面的先买(出)。

 2、Map:key-value,取、查询东西时用一个key(object),得到值(object),对象和对象联系在一起。

三、批量放入东西到袋子,Arrays,Collections

  1、Arrays:返回一个List.

     1.1  Arrays.asList(1,2,3,4,5) :

          List<Integer> list = Arrays.asList(16, 17, 18, 19, 20);//但是如果直接赋值,就相当一个数组,袋子大小不能变,list.add(),list.del(),增加和减少袋子都出错。

     1.2 持有一个数组:Integer[] moreInts={6,7,8}, Arrays.asList(moreInts)           

  2、Collections:addAll()

       2.1、Collection的一个对象,list:collection.addAll(Arrays.asList(moreInts)):子类会重写这个方法,当定义时,指定谁时,用谁的方法。

     2.2 、Collections

           1》Collection的一个对象+列表:Collections.addAll(collection, 11, 12, 13, 14, 15);
    2》Collection的一个对象+一个数组 Collections.addAll(collection, moreInts);

     Collections 比Collection 的addAll好用。

  2.3、

    1》构造函数有初始化值+Collections.addAll()

    2》构造函数无初始化值+Collections.addAll()    

   2》比1》快

 例子:Collection只是一个接口,具体的容器是ArrayList.

 public static void main(String[] args) {
//1构造函数有初始化值,Collections.addAll
Collection<Integer> collection = new ArrayList<Integer>(Arrays.asList(1, 2, 3, 4, 5));
Integer[] moreInts = { 6, 7, 8, 9, 10 };
collection.addAll(Arrays.asList(moreInts));

Collections.addAll(collection, 11, 12, 13, 14, 15);

Collections.addAll(collection, moreInts);

        //2构造函数无初始化值,Collections.addAll

Collection<Integer> collection1 = new ArrayList<Integer>();

Collections.addAll(collection, moreInts);


List<Integer> list = Arrays.asList(16, 17, 18, 19, 20);//
list.set(1, 99); // OK -- modify an element

}

 



原创粉丝点击