zoukankan      html  css  js  c++  java
  • Thinking in Java——集合(Collection)

    一、ArrayList的使用(略)

    二、容器的基本概念

    (一)、Collection是集合类的基本接口

    主要方法:

    public interface Collection<E>{
      boolean add(E element);//向集合中添加元素,E代表泛型
      Iterator<E> iterator();//返回实现了Iterator接口的对象
    }

    关于:Iterator之后讲解。

    (二)、实现了Collection的子类:

    List:按照顺序插入保存元素。                  Set:该容器内不能有重复的元素                     Queue:按照队列的规则决定对象的顺序

    (三)、Map接口

    定义:一组成对的“键值对”对象,使用key查找value

    注:Map这是单独的接口,不属于Collection,所以以map结尾的类都不属于Collection

    (四)、根据上诉分析使用容器

    1、ArrayList向上转型为Collection,并通过Collection添加处理数据。(运用到的技术:父类引用指向子类对象,调用子类的方法)

    public class UpToCollection {
        public static void main(String [] args){
            ArrayList<Integer> arrayList = new ArrayList();
            for(int i=0; i<5; ++i){
                arrayList.add(i);
            }
            Collection<Integer> collection = arrayList;
            collection.add(5);
            //这里使用了foreach循环,只要实现了Iterator接口就能够使用foreach
            //Collection没有List的get方法,需要用Iterator来进行遍历
            for(Integer i: collection){
                System.out.println(i);
            }
        }
    }
    View Code

    2、添加一组元素

    public class AddElementToCollection {
        public static void main(String[]args){
            
            Collection<Integer> collection = new ArrayList<Integer>(Arrays.asList(1,2,3,4,5,6));
            //知识点1:利用Arrays这个静态类,将数组,或者一列数字转换为List
            //知识点2:ArrayList可以嵌套List创建
            /*知识点3:为什么不可以Collection<Integer> collection = 
             * Arrays.asList(1,2,3,4,5,6);,发现创建并没有问题,但是到下文的时候使用
             * collection.addAll(Arrays.asList(datas));是会报错的
             * 原因:因为Arrays.asList(1,2,3,4,5,6)创建的List是固定长度的List
             * 所以是无法执行add()方法的。
             */
            Integer [] datas = {7,8,9,10};
            /*知识点4:必须使用Integer作为类,不能使用int,否则会报错
             *因为之前Collection<Integer> collection,已经将泛型定为Integer
             *所以不能使用引用类型,得到输入的泛型是什么,就需要建立什么类的数组
            */
            collection.addAll(Arrays.asList(datas));
            for(Integer i: collection){
                System.out.println(i);
            }
            //上文为通过Collection往List中添加一组数据(数组,或者自定义的数据),下文介绍另一种方法
            
            Collections.addAll(collection, 11,12,13,14,15,16);
            Collections.addAll(collection, datas);
            //注:这是Collections类不是Collection类
        }
    }
    AddElementToCollection

    Collection添加元素的方法  优点:方法运行效率快。  缺点:但是需要创建一个Collection类,来作为对象

    Collections添加元素的方法 优点:方便,不需要创建Collection类。

    3、Collection类型的作用:统一类型添加,删除。。。(统一遍历是由Iterator确定的)

    public class CollectionEffect {
        //统一各种容器,只需要一种方法就能添加,删除
        public static void main(String[] args){
            print(fill(new ArrayList<String>()));
            print(fill(new HashSet<String>()));
            print(fill(new HashMap<String,String>()));
        }
        //Collection接口的集合
        public static Collection<String> fill(Collection<String> c){
            c.add("dog");
            c.add("cat");
            c.add("pig");
            return c;
        }
        //重载fill方法,提供Map接口
        public static Map<String,String> fill(Map<String,String> map){
            map.put("dog", "pig");
            map.put("cat","small");
        
            return map;
        }
        
        public static void print(Collection<String> c){
            
        }
        
        public static void print(Map<String,String> map){
            
        }
    }
    CollectionEffect

    三、迭代器(Iterator)

    作用:统一遍历各种容器

    接口方法:

    public interface Iterator<E>{
      E next();//获取下一个元素
      boolean hasNext();//查看是否存在下一个元素
      void remove();//移除元素
    }
    Iterator

     注意:1.在使用next()方法前需要使用hasNext();

             2.next()和remove()是成对存在的。

    使用:

    public class UseIterator {
        public static void main(String[]args){
            ArrayList<Integer> arrayList = new ArrayList();
            for(int i=0; i<5; ++i){
                arrayList.add(i);
            }
            //获取Iterator,该方法是从Collection接口继承下来的
            Iterator<Integer> iterator = arrayList.iterator();
            //使用
            while(iterator.hasNext()){
                Integer x = iterator.next();
                System.out.println(x);
                iterator.remove();
            }
        }
    }
    UseIterator

    统一遍历:修改CollectionEffect.java中的print方法,

    //...接上文
    public static void print(Iterator<String> iterator){
        while(iterator.hasNext()){
            System.out.println(iterator.next());
        }
    }
        
    CollectionEffect

    四、具体的集合

    ①、ArrayList:可动态增长和缩减的数组,便于搜索,不利于插入和删除。   详解:略。

    ②、LinkedList:由链表组成的序列,便于插入,和删除,不利于查找。LinkedList还提供了使用其做栈和队列或双端队列的方法。导致LinkedList的Iterator与其他集合不同,所以等会会统一介绍。

    让LinkedList实现Stack(已经有了Stack这个类,但是LinkedList可以产生更好的Stack)

    public class LinkedListStack<T> {
        private LinkedList<T> mLinkedList;
        public LinkedListStack(){
            mLinkedList = new LinkedList<T>();
        }
        //入栈
        public void push(T view){
            mLinkedList.add(view);
        }
        //获取栈顶元素
        public T peek(){
            return mLinkedList.getFirst();
        }
        //移除栈顶元素
        public T pop(){
            return mLinkedList.removeFirst();
        }
        
        public boolean isEmpty(){
            return mLinkedList.isEmpty();
        }
        public String toString(){
             return mLinkedList.toString();
        }
    }
    LinkedListStack

    其他暂不实现。

    LinkedList的迭代器ListIterator

    1、只能用于各种List类的方法。

    2、作用:Iterator只能向前移动,ListIterator可以双向移动。

    public class UseListIterator {
        public static void main(String[] args){
            LinkedList<Integer> linkedList = new LinkedList<Integer>();
            for(int i=0; i<10; ++i){
                linkedList.add(i);
            }
            //获取ListIterator
            ListIterator<Integer> listIterator = linkedList.listIterator();
            //linkedList.listIterator(3); 让Iterator从第三这个位置开始遍历
            while(listIterator.hasNext()){
                int i = listIterator.next();
                System.out.println(i);
                //新特性 1:能够修改当前位置的数据
                listIterator.set(5);
                //特性2:能够向前移动,并获取数据
                listIterator.hasPrevious();
                listIterator.previous();
            }
        }
    }
    UseListIterator

    ③、Set:不保存重复的元素。

    散列集(Hasing):读取数据不按照存储数据时候的排序(随机排序),能够快速查找到所需要的对象。

    原理:散列表为每个对象计算一个整数,称为散列码。散列码是由对象实例域产生的整数(具体产生的算法不管)、

    注:如果是自定义类,就要负责实现这个类的hashCode,自己实现的hashCode方法要与equals方法兼容(就是如果有一个返回true则全都应该返回true)

    在JAVA中散列表由链表数组实现(就是有一串数组,每个数组存放的是一个链表),这串数组中的每个位置叫做“桶”。

    桶的作用:解决散列码相同的情况、当散列码相同的时候就将该数据放入桶的链表中。之后查询到该桶的时候遍历该桶的链表。

    小知识:当插入的数据太多,有可能导致桶被沾满的情况,所以当桶被占用超过75%的时候,就会进行再散列(创建新的表增加桶的数量,将旧表的数据移到新表)。

    树集(Tree):是一个有序集合,可以用任何顺序将元素插入到集合中,但遍历取出的时候,每个值自动按照排序后的顺序实现。(每将一个元素添加到树中,都被放置到正确的位置)

    问:Tree如何知道希望每个元素怎样排列?

    重写Comparator接口,并传入到TreeSet<E>中。

    public class UseTreeSet {
        public static void main(String[]args){
            //为TreeSet添加比较的逻辑
            Comparator<Integer> compatator = new Comparator(){
    
                @Override
                public int compare(Object o1, Object o2) {
                    // TODO Auto-generated method stub
                    //这里写逻辑
                    return 0;
                }
                
            };
            TreeSet<Integer> treeSet = new TreeSet(compatator);
        }
    }
    UseTreeSet

     所以说:要使用TreeSet的步骤是①、创建类并实重写equal()和hashCode()②、创建Comparator接口,并重写coparator()方法 ③、将Comparator对象传入TreeSet中

    队列(Queen):ArrayDeque和LinkedList实现。且这两个类都实现了双端队列(就是在链表的头尾都可进行添加和删除),LinkedList实现了Queue接口ArrayDeque实现了Deque接口。同时还有一个特殊的队列“优先级队列(Priority queue)”,任意插入,按照优先级的排列进行读取。(优先级是跟Tree一样,通过重写Coparator接口来进行排序的,如果没有重写Coparator则进行自然排序——调用对象equal()方法)。

    映射表(Map):通过自己设置的键(key)查找对应的值(value)。因为Map不属于Collection那么,如何遍历Map的key,或Map的value,还有key与value同时遍历

    1、遍历键的信息

    HashMap<String,String> map = new HashMap();
            map.put("123","asda");
            map.put("234","zxczxc");
            map.put("asd", "zxcdd");
            //遍历Map中的所有键
            Set<String> set = map.keySet();//通过获取Set映射表中的所有的键
            //注:该Set不是HashSet也不是TreeSet,只是实现了Set接口的类
            for (String str : set){
                System.out.println(str);
            }
    遍历键的信息

    2、遍历值的信息

    //接上
            //遍历所有值
            Collection<String> collection = map.values();//获取Collection获取值
            for (String str : collection){
                System.out.println(str);
            }
    遍历值

    3、全部遍历

            //全部遍历
            for (Map.Entry<String,String> mapData : map.entrySet()){
                String key = mapData.getKey();
                String value = mapData.getValue();
            }
    View Code

    五、自定义Collection和Iterator

    1、通过继承Collection接口实现方法   缺点:Collection需要重写的方法太多了,需要耗费大量的精力

    2、所以JAVA提供了AbstactCollection方法,完成了大部分Collection方法   缺点:当一个类已经继承其他类的时候,必须重写Collection。

    3、直接重写Iterator接口。

  • 相关阅读:
    2016第17周四
    2016第17周三
    2016第17周二
    OSGI框架学习
    2016年第16周日
    2016第16周六
    如何培养技术洞见力
    2016第15周四
    深入浅出ClassLoader
    Linux智能小开关rfkill
  • 原文地址:https://www.cnblogs.com/rookiechen/p/5509546.html
Copyright © 2011-2022 走看看