Java Collection集合

Collection集合

collection集合.png
  • collection集合作为List集合和Set集合共有的父类拥有着List集合和Set集合共有的属性和方法,这里总结常用的方法。
    • add(E e):添加单个元素
    • addAll(Collection<? extends E> c):将指定的Collection中的元素一次性添加到此Collection中
    • clear():清除collection中的所有元素。
    • contains(Object o):判断该集合是否包含某个元素返回值是Boolean类型
    • remove(Object o):移除某个指定的元素返回值boolean类型
    • isEmpty():判断该集合是否为空返回值Boolean类型
    • iterator() :集合迭代器用来遍历集合(这个很常用)
    • toArray():将集合转为数组进行返回
public class Demo_Collection {
    public static void main(String[] args) {
        Collection collection = new ArrayList();
        Demo_add(collection);
        Demo_isEmpty(collection);
        Demo_contains(collection,"胡歌");
        Demo_remove(collection,"杨紫");
        Demo_iterator(collection);
        Demo_toArray(collection);
        Demo_clear(collection);
    }
    private static void Demo_add(Collection collection) {
        collection.add("胡歌");
        collection.add("迪丽热巴");
        System.out.println(collection);
        String[] str = {"张一山", "杨紫"};
        collection.addAll(Arrays.asList(str));
        System.out.println(collection);
    }
    private static void Demo_isEmpty(Collection collection) {
        boolean empty = collection.isEmpty();
        if (empty){
            System.out.println("集合为空");
        }else {
            System.out.println("集合不为空");
        }
    }
    private static void Demo_contains(Collection collection, String value) {
        boolean b = collection.contains(value);
        if (b){
            System.out.println("找到"+value);
        }else {
            System.out.println("集合中不存在"+value);
        }
    }
    private static void Demo_remove(Collection collection, String value) {
        boolean b = collection.remove(value);
        if (b){
            System.out.println("成功移除"+value);
            System.out.println(collection);
        }
    }
    private static void Demo_iterator(Collection collection) {
        //这里利用迭代器对集合进行遍历
        Iterator iterator = collection.iterator();
        System.out.println("-------迭代器进行遍历------");
        while (iterator.hasNext()){
            String value = (String) iterator.next();
            System.out.println(value);
        }
        //对集合进行遍历的第二种方法
        System.out.println("-----增强for循环进行遍历-----");
        for (Object o : collection) {
            System.out.println(o);
        }
    }
    private static void Demo_toArray(Collection collection) {
        Object[] array = collection.toArray();
        System.out.println("-----for循环遍历该数组------");
        for (int i = 0; i < array.length; i++) {
            System.out.println(array[i]);
        }
        System.out.println("------增强for遍历该数组------");
        for (Object o : array) {
            System.out.println(o);
        }
    }
    private static void Demo_clear(Collection collection) {
        collection.clear();
        System.out.println(collection);
    }

}
  • 其中Collection集合包括其下的List和Set集合都是单列的,而且也是无序的
  • Collection集合是一个抽象类,它有一个Collections的工具类里面是一些List和Set集合都能使用的方法。
  • Collections类:此类完全由在 collection 上进行操作或返回 collection 的静态方法组成。它包含在 collection 上操作的多态算法,即“包装器”,包装器返回由指定 collection 支持的新 collection,以及少数其他内容。 (注:此类所以的方法都是静态方法,都是使用Collections.XXX()直接调用,<u>如果()内所传入的Collection对象或类为null程序会抛出NullPointerException</u>)
    • shuffle(List<?> list):打乱元素的顺序
    • sort(List<?> list):对元素进行默认升序排序
    • copy(List<? super T> dest, List<? extends T> src): 将所有元素从一个列表复制到另一个列表
public class Demo_Collections {
    public static void main(String[] args) {
        Collection<Integer> collection = new ArrayList<Integer>();
        for (int i = 0; i < 10; i++) {
            collection.add(i);
        }
        System.out.println("原始数据:" + collection);
        Collections.shuffle( (List<Integer>)collection);
        System.out.println("打乱之后的数据:" + collection);
        Collections.sort((List<Integer>) collection);
        System.out.println("排序之后的数据:" + collection);
        Collection<Integer> collection1 = new ArrayList<>();
        collection1.add(10);
        collection1.add(11);
        System.out.println(collection1);
        Collections.copy((List<Integer>)collection,(List<Integer>)collection1);
        System.out.println(collection);
    }

}

这里有一个问题,自定义的数据如何进排序。这里看一下官方文档给的sort函数的说明:

“根据元素的自然顺序 对指定列表按升序进行排序。列表中的所有元素都必须实现 Comparable 接口。此外,列表中的所有元素都必须是可相互比较的(也就是说,对于列表中的任何 e1 和 e2 元素,e1.compareTo(e2) 不得抛出 ClassCastException)。”

意思就是要重写Comparable接口

public class Person implements Comparable<Person>{
    private int age;
    private String name;
    @Override
    public String toString() {
        return "Person{" +
                "age=" + age +
                ", name='" + name + '\'' +
                '}';
    }
    public Person(int age, String name) {
        this.age = age;
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
    @Override
    public int compareTo(Person o) {
        //这里根据年龄判断
        return this.getAge()-o.getAge();//这里this-O代表的是升序,反之代表的是降序
    }
}

List集合

官方解释:有序的 collection(也称为序列)。此接口的用户可以对列表中每个元素的插入位置进行精确地控制。用户可以根据元素的整数索引(在列表中的位置)访问元素,并搜索列表中的元素。

特点:

  1. List集合是有序的,即元素的存储顺序是一致的
  2. List集合是允许重复的
  3. List集合是有索引的,所以有一些带有索引的方法
    • add(int index,E e):在指定位置插入元素
    • get(int index):返回指定位置的元素
    • remove(int,index):移除指定位置的元素
    • set(int index,E e):更改指定位置的元素
public class Demo_ArrayList {
    public static void main(String[] args) {
        ArrayList<String> arrayList = new ArrayList<>();
        String[] strings={"胡歌","迪丽热巴","张一山","杨紫"};
        arrayList.addAll(Arrays.asList(strings));
        System.out.println(arrayList);
        Demo_add(arrayList);
        Demo_get(arrayList,2);
        Demo_remove(arrayList,2);
        Demo_set(arrayList,2,"赵丽颖");
    }

    private static void Demo_set(ArrayList<String> arrayList, int i, String name) {
        String s = arrayList.set(i, name);
        System.out.println(s+"被更改为:"+name);
        System.out.println(arrayList);
    }

    private static void Demo_remove(ArrayList<String> arrayList, int i) {
        String s = arrayList.remove(i);
        System.out.println(s+"被删除");
        System.out.println(arrayList);
    }

    private static void Demo_add(ArrayList<String> arrayList) {
        arrayList.add(2,"古力娜扎");
        System.out.println(arrayList);
    }
    private static void Demo_get(ArrayList<String> arrayList, int i) {
        String s = arrayList.get(i);
        System.out.println(i+"号元素是:"+s);
    }
}

ArrayList和Vector集合

着两个集合功能和用法差不多,他们底层都是由可变的数组实现的,所以这两个集合的查询速度快,而至善速度相对较慢。Vector集合是JDK1.0版本开始存在的,后面就慢慢被ArrayList所代替了,其中ArrayList是不不同步的

LinkedList集合

List 接口的链接列表实现。实现所有可选的列表操作,并且允许所有元素(包括 null)。除了实现 List 接口外,LinkedList 类还为在列表的开头及结尾 getremoveinsert 元素提供了统一的命名方法。这些操作允许将链接列表用作堆栈、队列双端队列

注意,此实现不是同步的,ArrayList也是不同步的。

特点:

  1. LinkedList集合底层是基于链表实现的,和数组有相反的特性,查询慢,增删快。
  2. 因为链表的实现所以该集合包含了大量的首位操作的方法。
  3. 使用LinkedList集合特有的方法时不能使用多态。

常用方法:

    - public void addFirst(E e):将指定元素插入此列表的开头。
    - public void addLast(E e):将指定元素添加到此列表的结尾。
    - public void push(E e):将元素推入此列表所表示的堆栈。
    - public E getFirst():返回此列表的第一个元素。
    - public E getLast():返回此列表的最后一个元素。
    - public E removeFirst():移除并返回此列表的第一个元素。
    - public E removeLast():移除并返回此列表的最后一个元素。
    - public E pop():从此列表所表示的堆栈处弹出一个元素。
    - public boolean isEmpty():如果列表不包含元素,则返回true。
public class Demo_LinkedList {
    public static void main(String[] args) {
        LinkedList<String> linkedList = new LinkedList<>();
        String[] strings = {"胡歌", "古天乐", "张一山", "杨紫"};
        linkedList.addAll(Arrays.asList(strings));
        System.out.println("原始数据:" + linkedList);
        Demo_addFirst(linkedList);
        Demo_addLast(linkedList);
        Demo_pop(linkedList);
        Demo_getFirstAndLast(linkedList);
        Demo_remove(linkedList);
        Demo_isEmpty(linkedList);
    }

    private static void Demo_isEmpty(LinkedList<String> linkedList) {
        boolean b = linkedList.isEmpty();
        if (b){
            System.out.println("集合为空");
        }else {
            System.out.println("集合不为空");
        }
    }

    private static void Demo_remove(LinkedList<String> linkedList) {
        String first = linkedList.removeFirst();
        String last = linkedList.removeLast();
        System.out.println("移除First:"+first);
        System.out.println("移除Last:"+last);
        System.out.println("Demo_remove:"+linkedList);
    }
    private static void Demo_getFirstAndLast(LinkedList<String> linkedList) {
        String first = linkedList.getFirst();
        String last = linkedList.getLast();
        System.out.println("First:" + first);
        System.out.println("Last:" + last);
    }

    private static void Demo_pop(LinkedList<String> linkedList) {
        String s = linkedList.pop();
        System.out.println("Demo_pop:" + s);
        System.out.println("Demo_pop:" + linkedList);
    }

    private static void Demo_addLast(LinkedList<String> linkedList) {
        linkedList.addLast("赵丽颖");
        System.out.println("Demo_addLast:" + linkedList);
    }

    private static void Demo_addFirst(LinkedList<String> linkedList) {
        linkedList.addFirst("迪丽热巴");
        System.out.println("Demo_addFirst:" + linkedList);
    }
}

Set集合

官方定义:一个不包含重复元素的 collection。更确切地讲,set 不包含满足 e1.equals(e2) 的元素对 e1e2,并且最多包含一个 null 元素。正如其名称所暗示的,此接口模仿了数学上的 set 抽象。

特点

  1. 无序的,set集合是一个无序的集合,其下的子集HashSet,TreeSet等都是无序的,但是LinkedHashSet是一个有序的集合。
  2. 不允许重复的元素。这里判断重复的元素是顾具对象的hashcode值和equals方法进行判断的。所以在存储自定义对象的时候要重新对象的hashcode和equal方法。
  3. 因为没有索引,所以不能使用普通的方法进行集合的遍历。

特有方法:set集合基本上没有自己的特有的方法,都是从collection接口继承过来的一些方法。

public class Demo_Set {
    public static void main(String[] args) {
        Set<String> set = new HashSet<>();
        set.add("胡歌");
        set.add("迪丽热巴");
        set.add("古力娜扎");
        set.add("马儿扎哈");
        //set集合的两种遍历方式
        System.out.println("====增强for遍历====");
        for (String s : set) {
            System.out.print(s+"  ");
        }
        System.out.println();
        System.out.println("====iterator迭代器遍历====");
        Iterator<String> iterator = set.iterator();
        while (iterator.hasNext()){
            String s = iterator.next();
            System.out.print(s+"  ");
        }
    }
}

HashSet和TreeSet集合

HashSet:此类实现 Set 接口,由哈希表(实际上是一个 HashMap 实例)支持。它不保证 set 的迭代顺序;特别是它不保证该顺序恒久不变。此类允许使用 null 元素。 注意,此实现不是同步的。

HashSet的底层结构:哈希表=数组+链表(注:JDK1.8之后就是数组+链表/红黑树)

具体过程:
HashSet底层结构图.png

TreeSet:基于 TreeMapNavigableSet 实现。使用元素的自然顺序对元素进行排序,或者根据创建 set 时提供的 Comparator 进行排序,具体取决于使用的构造方法。注意,此实现不是同步的

LinkedHashSet集合

具有可预知迭代顺序的 Set 接口的哈希表和链接列表实现。此实现与 HashSet 的不同之外在于,后者维护着一个运行于所有条目的双重链接列表。此链接列表定义了迭代顺序,即按照将元素插入到 set 中的顺序(插入顺序)进行迭代。注意,插入顺序 受在 set 中重新插入的 元素的影响。(如果在 s.contains(e) 返回 true 后立即调用 s.add(e),则元素 e 会被重新插入到 set s 中。) 注意,此实现不是同步的

特点:

  • 有序的,多了一条链表来记录元素存储的顺序
  • 不允许重复的
  • 用法和其他set集合一样。
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 216,544评论 6 501
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,430评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 162,764评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,193评论 1 292
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,216评论 6 388
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,182评论 1 299
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,063评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,917评论 0 274
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,329评论 1 310
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,543评论 2 332
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,722评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,425评论 5 343
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,019评论 3 326
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,671评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,825评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,729评论 2 368
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,614评论 2 353

推荐阅读更多精彩内容