Java笔记之集合(二十)

一、Set 接口

1.基本介绍

  1. 它是一个无序(添加和取出的顺序不一致),没有索引
  2. 不允许有重复元素,可以有一个null
  3. Set接口和List接口一样,也是Collection 的子接口,因此,常用方法和 Collection 接口一样

基本结构
在这里插入图片描述

其中比较常用是实现类有HashSet和TreeSet

Set接口的遍历方式

  1. 可以使用迭代器遍历
  2. 使用增强for循环

注意:不能通过索引的方式来获取元素遍历,因为set接口是没有索引的

因为Set接口和List接口的常用方法类似,看一下API即可,需要注意的是该接口的实现类不允许有重复元素;也可以有null值

二、HashSet

基本结构
在这里插入图片描述

  1. HashSet底层源码实际上是创建了一个HashMap
    在这里插入图片描述
  2. 可以存放null值,但只能有一个null
  3. 不能保证存放元素的顺序和取出顺序一致
  4. 不能有重复元素/对象
import java.util.HashSet;
class test1{
    @SuppressWarnings({"all"})
    public static void main(String[] args){

        //add方法会返回一个boolean,不能有重复的数据
        HashSet hashSet = new HashSet();
        System.out.println(hashSet.add(1)); //true
        System.out.println(hashSet.add(2)); //true
        System.out.println(hashSet.add(1)); //false
        System.out.println(hashSet.add(3)); //true
        System.out.println(hashSet);    //[1, 2, 3]

        HashSet hashSet1 = new HashSet();
        hashSet1.add("张三");
        hashSet1.add("李四");
        hashSet1.add(new Person("小明"));
        hashSet1.add(new Person("小明")); //因为他们在堆中开辟了两个空间,是两个不同的对象
        System.out.println(hashSet1);   //[李四, 张三, 小明, 小明]
    }
}

class Person{
    String name;

    public Person(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return name;
    }
}

经典面试题

import java.util.HashSet;
class test1{
    @SuppressWarnings({"all"})
    public static void main(String[] args){
        //思考为什么两个不同的对象,只有添加进去一个值
        HashSet hashSet = new HashSet();
        hashSet.add(new String("张三"));
        hashSet.add(new String("张三"));
        System.out.println(hashSet);    //[张三]

		//解析
		/*
		首先该题目的创建String对象时调用String类中的构造器 ,第一次 new String("张三"),
		它会在堆里创建一个private final char value[]属性,然后指向常量池判断是否有张三,
		如果有 直接指向,如果没有就创建,显然第一次new String("张三")是没有的,而第二次
		new String("张三") 则是直接指向常量池中的张三
		而String中equals方法就是内容是否相等,如果相等就放弃添加,可以看下面的HashSet添加元素底层解析
		*/
    }
}

1.HashSet添加元素底层解析

  1. HashSet底层是HashMap
  2. 添加一个元素时,先得到该元素的hash值,对hash值进行运算,得到一个索引值
  3. 找到存储数据表table,看这个索引位置是否已经有元素
  4. 如果没有元素,直接加入
  5. 如果有,调用equals比较(可以重写equals方法,比较逻辑可以由程序员控制) 比如String比较的就是内容,如果相等,就放弃添加,如果不想等则以链表的方式添加

2.HashSet扩容机制

  1. HashSet底层是HashMap,第一次添加是,table数组扩容到16,临界值是threshold为12,threshold=加载因子loadFactor为0.75*16=12
  2. 如果table数组使用到了临界值12,就会扩容到162 = 32,新的临界值= 320.75 = 24;以此类推
  3. 在java1.8中,如果一条链表的元素个数TREEIFY_THRESHOLD到达默认值8,索引大小MIN_TREEIFY_CAPACITY超过默认值64;则就会树化(红黑树)

3.题目练习

练习题一

定义一个 Employee 类,该类包含:private 成员属性 name,age
要求:
1.创建 3 个 Employee 对象放入 HashSet 中
2.当 name 和 age 的值相同时,认为是相同员工, 不能添加到 HashSet 集合中

import java.util.HashSet;
import java.util.Objects;

class test1{
    @SuppressWarnings({"all"})
    public static void main(String[] args){
        //思考为什么两个不同的对象,只有添加进去一个值
        HashSet hashSet = new HashSet();
        hashSet.add(new Employee("tom",18));
        hashSet.add(new Employee("juck",20));
        hashSet.add(new Employee("tom",18));
        System.out.println(hashSet);
    }
}

class Employee{
    private String name;
    private int age;

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

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

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Employee employee = (Employee) o;
        return age == employee.age &&
                name.equals(employee.name);
    }

    @Override
    public int hashCode() {
        return Objects.hash(name, age);
    }
}

上面代码重写hashCode和equals代码解析
在这里插入图片描述
equals():
如果创建两个对象,name和age相同时 则他们的equals()为true
如果不重写equals()方法,他们就是创建了两个不同的对象,equals()就不相同为false

练习题二

定义一个 Employee 类,该类包含:private 成员属性 name,salary,birthday (MyDate类),其中birthday为MyDate类型(属性包括:year、month、day)
要求:
1.创建 3 个 Employee 对象放入 HashSet 中
2.当 name 和 birthday 的值相同时,认为是相同员工, 不能添加到 HashSet 集合中

import java.util.HashSet;
import java.util.Objects;

class test1{
    @SuppressWarnings({"all"})
    public static void main(String[] args){
        HashSet hashSet = new HashSet();
        hashSet.add(new Employee("tom",5000,new MyDate(1999,1,1)));
        hashSet.add(new Employee("tom",5000,new MyDate(1998,2,2)));
        hashSet.add(new Employee("tom",10000,new MyDate(1999,1,1)));
        System.out.println(hashSet);    
        //[Employee{name='tom', salary=5000, birthday=MyDate{year=1998, month=2, day=2}}, 
        // Employee{name='tom', salary=5000, birthday=MyDate{year=1999, month=1, day=1}}]
    }
}

class Employee{
    private String name;
    private int salary;
    private MyDate birthday;

    public Employee(String name, int salary, MyDate birthday) {
        this.name = name;
        this.salary = salary;
        this.birthday = birthday;
    }

    @Override
    public String toString() {
        return "Employee{" +
                "name='" + name + '\'' +
                ", salary=" + salary +
                ", birthday=" + birthday +
                '}';
    }

    //因为要求名字和日期相同,直接重写name和birthday的equals和hashCode方法即可
    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Employee employee = (Employee) o;
        return Objects.equals(name, employee.name) &&
                Objects.equals(birthday, employee.birthday);
    }

    @Override
    public int hashCode() {
        return Objects.hash(name, birthday);
    }
}

class MyDate{
    private int year;
    private int month;
    private int day;

    public MyDate(int year, int month, int day) {
        this.year = year;
        this.month = month;
        this.day = day;
    }

    @Override
    public String toString() {
        return "MyDate{" +
                "year=" + year +
                ", month=" + month +
                ", day=" + day +
                '}';
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        MyDate myDate = (MyDate) o;
        return year == myDate.year &&
                month == myDate.month &&
                day == myDate.day;
    }

    @Override
    public int hashCode() {
        return Objects.hash(year, month, day);
    }
}

三、LinkedHashSet

基本结构
在这里插入图片描述

  1. LinkedHashSet 是 HashSet的子类
  2. LinkedHashSet 底层就是一个 LinkedHashMap,底层维护了一个数组+双向链表,每一个结点有pre和next属性,这样可以形参一个双向链表
    在这里插入图片描述
  3. 在添加一个元素时,先求hash值,再求索引值,确定该元素在hashtable的位置,然后将添加的元素加入到双向链表(添加原理跟HashSet一样
  4. LinkedHashSet 根据元素的hashCode值来决定元素的存储位置,同时使链表维护元素的次序,这使得元素看起来是以插入顺序保存的,即有序的
  5. LinkedHashSet 不允许添加重复元素

1.题目练习

定义一个 Car类,该类包含:private 成员属性 name,price
要求:
1.创建 4 个 Car对象放入 LinkedHashSet中
2.当 name 和 price的值相同时,认为是相同员工, 不能添加到 LinkedHashSet集合中

import java.util.LinkedHashSet;
import java.util.Objects;

class test1{
    @SuppressWarnings({"all"})
    public static void main(String[] args){
        LinkedHashSet linkedHashSet = new LinkedHashSet();
        linkedHashSet.add(new Car("奥迪",300000));
        linkedHashSet.add(new Car("宝马",800000));
        linkedHashSet.add(new Car("奥迪",300000));
        linkedHashSet.add(new Car("奥迪",400000));
        System.out.println(linkedHashSet);
    }
}

class Car {
    private String name;
    private int price;

    public Car(String name, int price) {
        this.name = name;
        this.price = price;
    }

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

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Car car = (Car) o;
        return price == car.price &&
                Objects.equals(name, car.name);
    }

    @Override
    public int hashCode() {
        return Objects.hash(name, price);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

王博1999

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值