Collection集合

概述

继承体系

  • Collection 单列集合

Collection接口

概述

  • 单列集合的顶层接口,它表示一组对象,这些对象也被称为Collection的元素
  • JDK不提供此接口的任何直接实现,它提供更具体的子接口(如Set和List)实现

创建Collection集合的对象

  • 多态的方式
  • 具体的实现类ArrayList

Collection 集合常用方法

  • boolean add(E e)添加元素
  • boolean remove(Object o)从集合中移除指定的元素
  • boolean removeif(Object o)根据条件进行删除
    注意事项:
    1.removeif括号中可以使用lambda表达式
    2.removeif底层会遍历集合,得到集合中的每一个元素
    3.底层会把每一个元素放到lambda表达式中去判断,true就删除
  • void clear() 清空集合
  • boolean contains(Object o)判断集合中是否存在指定的元素
  • boolean isEmpty()判断集合是否为空
  • int size0集合的长度,也就是集合中元素的个数
public class CollectionDemo2 {
    public static void main(String[] args) {

        Collection<String> collection = new ArrayList<>();

        // - boolean add(E e)添加元素
        collection.add("aaa");
        collection.add("bbb");
        collection.add("ccc");

        System.out.println(collection); // [aaa, bbb, ccc]

        //- boolean remove(Object o)从集合中移除指定的元素
        boolean result = collection.remove("aaa");
        boolean result2 = collection.remove("ddd");
        System.out.println(result); // true
        System.out.println(result2); // false
        System.out.println(collection); // [bbb, ccc]

        //- boolean removeif(Object o) 根据条件进行删除
        // 注意事项,removeif括号中可以使用lambda表达式

        collection.removeIf((String s)->{
            return s.length() == 3; // 删除字符串长度为三的字符串
        });

        System.out.println(collection);// []

        collection.add("aaa");
        collection.add("bbb");
        collection.add("ccc");

        System.out.println(collection); // [aaa, bbb, ccc]

        //- void clear()清空集合
        collection.clear();

        System.out.println(collection); // []

        //- boolean contains(Object o)判断集合中是否存在指定的元素
        collection.add("aaa");

        System.out.println(collection.contains("aaa")); // true
        System.out.println(collection.contains("ddd")); // false

        //- boolean isEmpty()判断集合是否为空
        System.out.println(collection.isEmpty()); // false
        //- int size0集合的长度,也就是集合中元素的个数
        System.out.println(collection.size()); // 1

    }
}

Iterator

迭代器,集合专业遍历方式,是一个接口,我们无法直接使用,需要使用Iterator接口的实现类对象,获取实现类的方式比较特殊,Collection接口中有一个方法,叫Iterator(),这个方法返回的就是迭代器的实现类对象,Iterator<e> iterator()返回再此 collection 的元素上进行的迭代器。

使用步骤

1.使用集合中的方法iterator()获取迭代器的实现类对象,使用Iterator接口接收(多态)
2.使用Iterator接口当中的方法hasNext判断下还有没有下一个元素
3.使用Iterator接口中的方法next取出集合的下一个元素

常用方法:

public e next():返回迭代的下一个元素,取出元素后将迭代器往后移动一个索引
public boolean hasNext():如果仍有元素可以迭代,则返回true
default void remove():从底层集合中删除迭代器返回的最后一个元素(指向谁删除谁).

public class CollectionDemo3 {
    public static void main(String[] args) {
        Collection<String> coll = new ArrayList<>();
        //添加元素:
        coll.add("串串星人");
        coll.add("吐槽星人");
        coll.add("汪星人");
        //1.使用集合中的方法iterator()获取迭代器的实现类对象,使用Iterator接口接收(多态)
        //注意:Iterator<E>接口也是由泛型的,迭代器的泛型跟着集合走,集合是什么泛型,迭代器就是什么泛型

        Iterator<String> it = coll.iterator();
        //没有元素,在取出元素会抛出NoSuchElementException没有元素异常
        while(it.hasNext()){
            String e = it.next();
            System.out.println(e);
        }

        while(it2.hasNext()){
            String e = it2.next();
            if("串串星人".equals(e)){
                    it.remove();
            }
        }
        System.out.println("--------------------------------");
        for(Iterator<String> it3 = coll.iterator();it3.hasNext();){
            String e = it3.next();
            System.out.println(e);
        }
    }
}

继承体系

  • List 可重复
  • Set 不可重复

List 接口

概述

  • 有序的集合(存储和取出元素顺序相同)
  • 允许存储重复元素。
  • 有索引,可以使用普通的for循环遍历

    常用方法

    public void add(int index, E element): 将指定的元素,添加到该集合中的指定位置上。
    E remove(int index):删除指定索引处的元素,返回被删除的元素,也可以删除指定的元素
    E set(int index,E element):修改指定索引处的元素,返回被修改的元素
    E get(int index):返回指定索引处的元素

public class Demo01List {
    public static void main(String[] args) {
        //创建一个List集合对象,多态
        List<String> list = new ArrayList<>();
        //使用add方法往集合中添加元素
        list.add("a");
        list.add("b");
        list.add("c");
        list.add("d");
        list.add("a");
        System.out.println(list);//[a,b,c,d,a]

        //public void add(int index, E element)`: 将指定的元素,添加到该集合中的指定位置上。
        //在c和d之间添加z

        list.add(3,"z");

        System.out.println(list); // [a, b, c, z, d, a]

        // E remove(int index):删除指定索引处的元素,返回被删除的元素,也可以删除指定的元素
        list.remove(2);
        System.out.println(list); //[a, b, z, d, a]
        list.remove("d");
        System.out.println(list); // [a, b, z, a]

        //E set(int index,E element):修改指定索引处的元素,返回被修改的元素
        list.set(0,"s");
        System.out.println(list); //[s, b, z, d, a]

        // E get(int index):返回指定索引处的元素
        System.out.println(list.get(list.size()-1)); //a

    }
}

实现类

  • ArrayList
  • LinkedList

ArrayList底层

  • ArrList底层数据是数组,查询快,增删慢
  • 空参构造会创建一个长度为0的数组,当调用add方法会创建一个长度为10的数组,在底层叫做elementData,还会存在一个变量 size 它表达下一次要操作的索引,也表达数组元素的个数
  • 如果数组填满,数组会自动扩容,创建一个长度1.5倍的数组
  • 查询根据数组的地址址跟索引来获取,底层会判断你这个索引会不会大于等于size如果大于等于就报错

LinkedList

1.底层是一个链表结构,查询慢,增删快
2.里面包含了大量操作首尾元素的方法

public class LinkedListDemo1 {
    public static void main(String[] args) {
        LinkedList<String> linkedList = new LinkedList<>();
        linkedList.add("111");
        linkedList.add("222");
        linkedList.add("333");

        for (int i = 0; i < linkedList.size(); i++) {
            System.out.println(linkedList.get(i));
        }

        for (String s : linkedList) {
            System.out.println(s);
        }

        Iterator<String> iterator = linkedList.iterator();
        while (iterator.hasNext()){
            System.out.println(iterator.next());
        }
    }
}

特有方法

  • public void addFirst(E e)`:将指定元素插入此列表的开头。
  • public void addLast(E e)`:将指定元素添加到此列表的结尾。
  • public E getFirst()`:返回此列表的第一个元素。
  • public E getLast()`:返回此列表的最后一个元素。
  • public E removeFirst()`:移除并返回此列表的第一个元素。
  • public E removeLast()`:移除并返回此列表的最后一个元素。
  • public E pop()`:从此列表所表示的堆栈处弹出一个元素。
  • public void push(E e)`:将元素推入此列表所表示的堆栈。
  • public boolean isEmpty()`:如果列表不包含元素,则返回true。
public class LinkedListDemo2 {
    public static void main(String[] args) {
        LinkedList<String> linkedList = new LinkedList<>();
        linkedList.add("111");
        linkedList.add("222");
        linkedList.add("333");
        linkedList.add("444");
//        - public void addFirst(E e)`:将指定元素插入此列表的开头。
        linkedList.addFirst("000");
        System.out.println(linkedList); // [000, 111, 222, 333, 444]

//        - public void addLast(E e)`:将指定元素添加到此列表的结尾。
        linkedList.addLast("555"); 
        System.out.println(linkedList); // [000, 111, 222, 333, 444, 555]
//        - public E getFirst()`:返回此列表的第一个元素。
        System.out.println(linkedList.getFirst()); // 000
//        - public E getLast()`:返回此列表的最后一个元素。
        System.out.println(linkedList.getLast()); // 555
//        - public E removeFirst()`:移除并返回此列表的第一个元素。
        linkedList.removeFirst();
        System.out.println(linkedList); // [111, 222, 333, 444, 555]
//        - public E removeLast()`:移除并返回此列表的最后一个元素。
        linkedList.removeLast();
        System.out.println(linkedList); // [111, 222, 333, 444]
//        - public E pop()`:从此列表所表示的堆栈处弹出一个元素。
        System.out.println(linkedList.pop()); // 111
//        - public void push(E e)`:将元素推入此列表所表示的堆栈。
        linkedList.push("push");
        System.out.println(linkedList); // [push, 222, 333, 444]
//        - public boolean isEmpty()`:如果列表不包含元素,则返回true。
        System.out.println(linkedList.isEmpty()); // false

    }
}


Set 接口

特点

  • Set不可重复
  • 存储顺序不一致
  • 没有带索引的方法,所有不能使用普通for循环,也不能通过索引来获取,删除Set集合里面的元素
public class SetDemo1 {
    public static void main(String[] args) {
        Set<String> set = new TreeSet<>();
        set.add("ddd");
        set.add("aaa");
        set.add("aaa");
        set.add("bbb");
        set.add("ccc");

        for (String s : set) {
            System.out.println(s);
        }
        Iterator<String> iterator = set.iterator();
        while (iterator.hasNext()){
            System.out.println(iterator.next());
        }
    }
}

实现类

  • HashSet
  • TreeSet

TreeSet

特点

  • 不包含重复元素的集合
  • 没有带索引的方法
  • 可以将元素按照规则进行排序
  • 想要使用TreeSet存储自定义对象,需要制定排序规则
public class TreeSetDem01 {
    public static void main(String[] args) {
        TreeSet<Integer> ts = new TreeSet<>();
        ts.add(5);
        ts.add(3);
        ts.add(4);
        ts.add(1); 
        ts.add(2);
        System.out.println(ts); // [1, 2, 3, 4, 5]
    }
}

自然排序Comparable的使用

  • 使用空参构造创建TreeSet集合
  • 自定义的Student类实现Comparable接口
  • 重写里面的comparaTo方法

原理

  • 如果重写的方法返回值为负数,表示当前存入的元素是较小值,存左边
  • 如果返回值为0,表示当前存入的元素跟集合中元素重复了,不存
  • 如果重写的方法返回值为正数,表示当前存入的元素是较大值,存右边
public class Student implements Comparable<Student> {
    private String name;
    private int age;

    public Student() {
    }

    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

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

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }

    @Override
    public int compareTo(Student o) {
        // 按照对象的年龄进行排序,年龄一样在按照姓名排序,
        int result = this.age - o.age;
        result = result == 0? this.name.compareTo(o.getName()) : result;
        return result;
    }
}

public class TreeSetDemo2 {
    public static void main(String[] args) {
        TreeSet<Student> treeSet = new TreeSet<>();

        Student s1 = new Student("张三",18);
        Student s2 = new Student("李四",22);
        Student s3 = new Student("王五",20);

        treeSet.add(s1);
        treeSet.add(s2);
        treeSet.add(s3);
        System.out.println(treeSet); // [Student{name='张三', age=18}, Student{name='王五', age=20}, Student{name='李四', age=22}]
    }
}

比较器排序Comparable的使用

  • TreeSet的带参构造方法使用的是比较器排序对元素进行排序的
  • 比较器排序,就是让集合构造方法接收Cpmparator的实现类对象,重写compareTo(T o1,T o2)方法
  • 重写方法的时候,一定要注意排序规则必须按照要求的主要条件和次要条件来写

    public class TreeSetDemo4 {
    public static void main(String[] args) {
        TreeSet<Teacher> treeSet = new TreeSet<>(new Comparator<Teacher>() {
            @Override
            public int compare(Teacher o1, Teacher o2) {
                // 主要条件
                int result = o1.getAge() - o2.getAge();
                // 次要条件
                result = result == 0 ? o1.getName().compareTo(o2.getName()):result;
                return result;
            }
        });
        Teacher t1 = new Teacher("zhangsan",23);
        Teacher t2 = new Teacher("lisi",23);
        Teacher t3 = new Teacher("wangwu",40);
    
        treeSet.add(t1);
        treeSet.add(t2);
        treeSet.add(t3);
    
        System.out.println(treeSet);
    }
    }
    public class Teacher {
    private String name;
    private int age;
    
    public Teacher() {
    }
    
    @Override
    public String toString() {
        return "Teacher{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
    
    public Teacher(String name, int age) {
        this.name = name;
        this.age = age;
    }
    
    public String getName() {
        return name;
    }
    
    public void setName(String name) {
        this.name = name;
    }
    
    public int getAge() {
        return age;
    }
    
    public void setAge(int age) {
        this.age = age;
    }
    }

注:在使用的时候,默认使用自然排序,当自然排序不满足现在的需求,使用比较器排序

HashSet

特点

  • 底层数据结构是哈希表
  • 不能保证存储和取出的顺序完全一致
  • 没有带索引方法,所以不能使用普通for循环遍历
  • 由于是Set集合,所以元素唯一
public class HashSetDemo1 {
    public static void main(String[] args) {
        HashSet<String> hs = new HashSet<>();

        hs.add("Hello");
        hs.add("World");
        hs.add("Java");
        hs.add("Java");
        hs.add("Java");
        hs.add("Html");
        hs.add("CSS");
        hs.add("JS");

        Iterator<String> iterator = hs.iterator();
        while (iterator.hasNext()){
            System.out.println(iterator.next());
        }

        for (String h : hs) {
            System.out.println(h);
        }
    }
}

哈希值

哈希值(哈希码值):是JDK根据对象的地址或者属性,算出来的int类型的整数

注:Object类中有一个方法可以获取对象的哈希值
public int hasCode():根据对象的地址值计算出来的哈希值

 特点

  • 如果没有重写hasCode方法,那么是根据对象的地址址计算出的哈希值,同一个对象多次调用hasCode()方法返回的哈希值是相同的,不同对象的哈希值是不一样的。
  • 如果重写了hasCode方法,一般都是通过对象的属性值计算出哈希值。如果不同的对象属性值是一样的,那么计算出来的的哈希值也是一样的。

Java底层实现

  • JDK8之前,底层采用数组+链表实现。
  • JDK8以后,底层进行了优化。由数组+链表+红黑树实现。

注:如果HashSet集合要存储自定义对象,那么必须重写hasCode和equals方法。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值