集合

来源:互联网 发布:淘宝详情页图片上传 编辑:程序博客网 时间:2024/06/06 11:01

集合

集合框架图

  • Collection
    • List
      • LinkedList
      • ArrayList
    • Set
      • HashSet
      • TreeSet

概述

  • Collection 是一个超级接口,List与Set是其子接口 Collection 提供了如下操作集合的方法
    1. boolean add(E e)
    2. void clear()
    3. boolean remove(Object o)
    4. int size()

List 接口

  • List(列表) 接口 通常允许重复的元素有序可有多个null,list提供了以下方法:
    1. E get(int index) 返回列表中指定位置的元素
    2. E set(int index, E element) 用指定元素替换列表中的指定位置的元素
    3. List subList(int fromIndex, int toIndex)

ArrayList 实现类

  • ArrayList 实际上是可变数组,有着线性表的优缺点,ArrayList 扩容为原来的1.5倍
    • 注意 ArrayList 是有默认长度的 为10
 /**     * Constructs an empty list with an initial capacity of ten.     */    public ArrayList() {        this(10);    }
  • 优点:随机访问速度快
  • 缺点:增删慢,线程不安全

四种遍历方法

List<String> list = new ArrayList<String>();        list.add("Hello");        list.add("World");        list.add("java");        // 第一种遍历 使用for循环遍历        for (int i = 0; i < list.size(); i++) {            System.out.print(list.get(i) + "  ");        }        System.out.println("第一种");        // 第二种遍历方法使用foreach遍历List        for (String str : list) {            System.out.print(str + "  ");        }        System.out.println("第二种");        // 第三种遍历,把链表变为数组相关的内容进行遍历        String[] strArray = new String[list.size()];        list.toArray(strArray);        for (int i = 0; i < strArray.length; i++)        // 这里也可以改写为foreach(String str:strArray)这种形式        {            System.out.print(strArray[i] + "  ");        }        System.out.println("第三种");        // 第四种遍历 使用迭代器进行相关遍历        Iterator<String> ite = list.iterator();        while (ite.hasNext()) {            System.out.print(ite.next() + "  ");        }        System.out.println("第四种");

LinkedList 实现类

  • LinkedList 是list接口的链表实现,实现所有可选的列表操作,并且允许所有元素(包括 null)。除了实现 List 接口外,LinkedList 类还为在列表的开头及结尾 get、remove 和 insert 元素提供了统一
  • 的命名方法。这些操作允许将链接列表用作堆栈、队列或双端队列。
  • 此类实现 Deque 接口,为 add、poll 提供先进先出队列操作,以及其他堆栈和双端队列操作。
    • 注意 此实现不是同步的,可以使用‘包装’该链表,最好在初始化完成该动作
    • 优点 :增删快
    • 缺点: 查询慢,要从头到尾一个个查找,线程不安全
List list = Collections.synchronizedList(new LinkedList(...));

Set 接口

  • Set(集合) 接口 不允许有重复元素无序最多有一个null元素

1. HashSet

  • 底层是基于HashMap实现的,其实HashSet就是map里面的Key
 /**     * Constructs a new, empty set; the backing <tt>HashMap</tt> instance has     * default initial capacity (16) and load factor (0.75).     */    public HashSet() {        map = new HashMap<>();    }

注意

  1. HashSet中存储元素的位置是固定的

    • 虽然HashSet中存储的元素是无序的,但是由于HashSet底层是基于Hash算法实现的,使用了HashCode,所以HashSet相应的元素位置是固定的
  2. HashSet 中能存放null之,但是只能存放一个null

  3. 遍历 方法与ArrayLIst方法一样

2. LinkedHsahSet

3. TreeSet

TreeSet是一种排序二叉树。存入Set集合中的值,会按照大小值的大小进行相关的排序操作,底层是基于红黑树来实现的
*TreeSet 与HashSet的区别与联系
1. HashSet是通过HashMap来实现的,TreeSet是通过TreeMap实现的,不过,Set用的Map的Key

原创粉丝点击