Collection集合

Collection集合

在这里插入图片描述

  • 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()直接调用,如果()内所传入的Collection对象或类为null程序会抛出NullPointerException
    • 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之后就是数组+链表/红黑树)

具体过程:[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-l8BQiYu0-1571120342371)(images\HashSet底层结构图.png)]

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

LinkedHashSet集合

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

特点:

  • 有序的,多了一条链表来记录元素存储的顺序
  • 不允许重复的
  • 用法和其他set集合一样。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值