Java面向对象之Set 接口实现类-LinkedHashSet 及 Map 接口和常用方法

1、Set 接口实现类-LinkedHashSet

1.1、LinkedHashSet 的全面说明

在这里插入图片描述
在这里插入图片描述

1.2、LinkedHashSet 代码实现

在这里插入图片描述

package set_;

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

@SuppressWarnings({"all"})
public class LinkedHashSetExercise {
    public static void main(String[] args) {
        LinkedHashSet linkedHashSet = new LinkedHashSet();
        linkedHashSet.add(new Car("奥拓", 1000));  // OK
        linkedHashSet.add(new Car("奥迪", 300000));  // OK
        linkedHashSet.add(new Car("法拉利", 10000000));  // OK
        linkedHashSet.add(new Car("奥迪", 300000));  // 加入不了
        linkedHashSet.add(new Car("保时捷", 70000000));  // OK
        linkedHashSet.add(new Car("奥迪", 300000));  // 加入不了
        System.out.println("linkedHashSet=" + linkedHashSet);
        /**
         * linkedHashSet=[
         * Car{name='奥拓', price=1000.0}, 
         * Car{name='奥迪', price=300000.0}, 
         * Car{name='法拉利', price=1.0E7}, 
         * Car{name='保时捷', price=7.0E7}]
         */
    }
}

/**
 * Car 类(属性:name,price), 如果 name 和 price 一样
 * 则认为是相同元素, 就不能添加
 */
class Car {
    private String name;
    private double price;

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

    public String getName() {
        return name;
    }

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

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

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

    // 重写 equals 方法 和 hashCode
    // 当 name 和 price 相同时, 就返回相同的 hashCode 值, equals 返回 true
    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Car car = (Car) o;
        return Double.compare(car.price, price) == 0 && Objects.equals(name, car.name);
    }

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

2、Map 接口和常用方法

2.1、Map 接口实现类的特点

在这里插入图片描述
在这里插入图片描述

package map_;

import java.util.HashMap;
import java.util.Map;

@SuppressWarnings({"all"})
public class Map_ {
    public static void main(String[] args) {
        // Map 接口实现类的特点, 使用实现类 HashMap
        // 1. Map 与 Collection 并列存在, 用于保存具有映射关系的数据: Key-Value(双列元素)
        // 2. Map 中的 key 和 value 可以是任何引用类型的数据, 会封装到 HashMap$Node 对象中
        // 3. Map 中的 key 不允许重复, 原因和 HashSet 一样, 分析过源码
        // 4. Map 中的 value 可以重复
        // 5. Map 的 key 可以为 null, value 也可以为 null, 注意 key 为 null, 只能有一个, value 为 null, 可以多个
        // 6. 常用 String 类作为 Map 的 key
        // 7. key 和 value 之间存在单向一对一关系, 即通过指定的 key 总能找到对应的 value
        Map map = new HashMap();
        map.put("no1", "赵敏");  // k-v
        map.put("no2", "张无忌");  // k-v
        map.put("no1", "张三丰");  // 当有相同的 k, 就等价于替换
        map.put("no3", "张三丰");  // k-v
        map.put(null, null);  // k-v
        map.put(null, "abc");  // 等价替换
        map.put("no4", null);  // k-v
        map.put("no5", null); //k-v
        map.put(1, "周芷若");  // k-v
        map.put(new Object(), "金毛狮王");  // k-v
        // 通过 get 方法, 传入 key, 会返回对应的 value
        System.out.println(map.get("no2"));  // 张无忌
        System.out.println("map=" + map);  // map={no2=张无忌, null=abc, no1=张三丰, 1=周芷若, no4=null, no3=张三丰, no5=null, java.lang.Object@1b6d3586=金毛狮王}
    }
}
2.2、Map 接口常用方法
package map_;

import java.util.HashMap;
import java.util.Map;

@SuppressWarnings({"all"})
public class MapMethod {
    public static void main(String[] args) {
        // map 接口常用方法
        Map map = new HashMap();
        map.put("邓超", new Book("", 100));  // OK
        map.put("邓超", "孙俪");  // 替换操作, 分析源码
        map.put("王宝强", "马蓉");  // OK
        map.put("宋喆", "马蓉");  // OK
        map.put("刘令博", null);  // OK
        map.put(null, "刘亦菲");  // OK
        map.put("鹿晗", "关晓彤");  // OK
        map.put("jack", "jack 的老婆");  // OK
        System.out.println("map=" + map);  // map={邓超=孙俪, 宋喆=马蓉, 刘令博=null, null=刘亦菲, 王宝强=马蓉, 鹿晗=关晓彤, jack=jack 的老婆}

        // remove: 根据键删除映射关系
        map.remove(null);
        System.out.println("map=" + map);  // map={邓超=孙俪, 宋喆=马蓉, 刘令博=null, 王宝强=马蓉, 鹿晗=关晓彤, jack=jack 的老婆}

        // get: 根据键获取值
        Object val = map.get("鹿晗");
        System.out.println("val=" + val);  // val=关晓彤

        // size: 获取元素个数
        System.out.println("size=" + map.size());  // size=6

        // isEmpty: 判断个数是否为 0
        System.out.println(map.isEmpty());  // false

        // containsKey: 查找键是否存在
        System.out.println("结果=" + map.containsKey("allen"));  // 结果=false

        // clear: 清除 k-v
        map.clear();
        System.out.println("map=" + map);  // map={}
    }
}

class Book {
    private String name;
    private int num;

    public Book(String name, int num) {
        this.name = name;
        this.num = num;
    }
}
2.3、Map 接口遍历方法

在这里插入图片描述
在这里插入图片描述

package map_;

import java.util.*;

@SuppressWarnings({"all"})
public class MapFor {
    public static void main(String[] args) {
        Map map = new HashMap();
        map.put("邓超", "孙俪");
        map.put("王宝强", "马蓉");
        map.put("宋喆", "马蓉");
        map.put("刘令博", null);
        map.put(null, "刘亦菲");
        map.put("鹿晗", "关晓彤");

        // 第一组: 先取出 所有的 Key, 通过 Key 取出对应的 Value
        Set keySet = map.keySet();

        // (1) 增强 for
        System.out.println("===第一种方式===");
        for (Object key : keySet) {
            System.out.println(key + "-" + map.get(key));
            /**
             * ===第一种方式===
             * 邓超-孙俪
             * 宋喆-马蓉
             * 刘令博-null
             * null-刘亦菲
             * 王宝强-马蓉
             * 鹿晗-关晓彤
             */
        }

        // (2) 迭代器
        System.out.println("===第二种方式===");
        Iterator iterator = keySet.iterator();
        while (iterator.hasNext()) {
            Object key = iterator.next();
            System.out.println(key + "-" + map.get(key));
            /**
             * ===第二种方式===
             * 邓超-孙俪
             * 宋喆-马蓉
             * 刘令博-null
             * null-刘亦菲
             * 王宝强-马蓉
             * 鹿晗-关晓彤
             */
        }

        // 第二组: 把所有的 values 取出来
        Collection values = map.values();
        // 这里可以使用所有的 Collections 使用的遍历方法
        // (1) 增强 for
        System.out.println("===取出所有的 value 增强 for===");
        for (Object value : values) {
            System.out.println(value);
            /**
             * ===取出所有的 value 增强 for===
             * 孙俪
             * 马蓉
             * null
             * 刘亦菲
             * 马蓉
             * 关晓彤
             */
        }

        // (2) 迭代器
        System.out.println("===取出所有的 value 迭代器===");
        Iterator iterator2 = values.iterator();
        while (iterator2.hasNext()) {
            Object value = iterator2.next();
            System.out.println(value);
            /**
             * ===取出所有的 value 迭代器===
             * 孙俪
             * 马蓉
             * null
             * 刘亦菲
             * 马蓉
             * 关晓彤
             */
        }

        // 第三组: 通过 EntrySet 来获取 k-v
        Set entrySet = map.entrySet();  // EntrySet<Map.Entry<K,V>>
        // (1) 增强 for
        System.out.println("===使用 EntrySet 的 for 增强(第 3 种)===");
        for (Object entry : entrySet) {
            // 将 entry 转成 Map.Entry
            Map.Entry m = (Map.Entry) entry;
            System.out.println(m.getKey() + "-" + m.getValue());
            /**
             * ===使用 EntrySet 的 for 增强(第 3 种)===
             * 邓超-孙俪
             * 宋喆-马蓉
             * 刘令博-null
             * null-刘亦菲
             * 王宝强-马蓉
             * 鹿晗-关晓彤
             */
        }

        // (2) 迭代器
        System.out.println("===使用 EntrySet 的 迭代器(第 4 种)===");
        Iterator iterator3 = entrySet.iterator();
        while (iterator3.hasNext()) {
            Object entry = iterator3.next();
            // System.out.println(entry.getClass());  // HashMap$Node 实现 -> Map.Entry (getKey, getValue)
            Map.Entry m = (Map.Entry) entry;
            System.out.println(m.getKey() + "-" + m.getValue());
            /**
             * ===使用 EntrySet 的 迭代器(第 4 种)===
             * 邓超-孙俪
             * 宋喆-马蓉
             * 刘令博-null
             * null-刘亦菲
             * 王宝强-马蓉
             * 鹿晗-关晓彤
             */
        }
    }
}
2.4、Map 接口小练习

在这里插入图片描述

package map_;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

@SuppressWarnings({"all"})
public class MapExercise {
    public static void main(String[] args) {
        // 代码实现
        Map hashMap = new HashMap();
        // 添加对象
        hashMap.put(1, new Emp("jack", 300000, 1));
        hashMap.put(2, new Emp("tom", 21000, 2));
        hashMap.put(3, new Emp("milan", 12000, 3));

        // 遍历 2 种方式
        // 并遍历显示工资>18000 的员工(遍历方式最少两种)
        // 1. 使用 keySet -> 增强 for
        Set keySet = hashMap.keySet();
        System.out.println("===增强 for===");
        for (Object key : keySet) {
            // 先获取 value
            Emp emp = (Emp) hashMap.get(key);
            if (emp.getSal() > 18000) {
                System.out.println(emp);
                /**
                 * ===增强 for===
                 * Emp{name='jack', sal=300000.0, id=1}
                 * Emp{name='tom', sal=21000.0, id=2}
                 */
            }
        }
        // 2. 使用 EntrySet -> 迭代器
        Set entrySet = hashMap.entrySet();
        System.out.println("===迭代器===");
        Iterator iterator = entrySet.iterator();
        while (iterator.hasNext()) {
            Map.Entry entry = (Map.Entry) iterator.next();
            // 通过 entry 取得 key 和 value
            Emp emp = (Emp) entry.getValue();
            if (emp.getSal() > 18000) {
                System.out.println(emp);
                /**
                 * ===迭代器===
                 * Emp{name='jack', sal=300000.0, id=1}
                 * Emp{name='tom', sal=21000.0, id=2}
                 */
            }
        }
    }
}

/**
 * 使用 HashMap 添加 3 个员工对象,要求
 * 键:员工 id
 * 值:员工对象
 * <p>
 * 并遍历显示工资>18000 的员工(遍历方式最少两种)
 * 员工类:姓名、工资、员工 id
 */
class Emp {
    private String name;
    private double sal;
    private int id;

    public Emp(String name, double sal, int id) {
        this.name = name;
        this.sal = sal;
        this.id = id;
    }

    public String getName() {
        return name;
    }

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

    public double getSal() {
        return sal;
    }

    public void setSal(double sal) {
        this.sal = sal;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    @Override
    public String toString() {
        return "Emp{" +
                "name='" + name + '\'' +
                ", sal=" + sal +
                ", id=" + id +
                '}';
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值