当前位置: 首页 > news >正文

枚举类常见用法,A Guide to Java Enums

目录

    • 啥是枚举类
    • Custom Enum Methods
    • Comparing Enum Types Using “==” Operator
    • Using Enum Types in Switch Statements
    • Fields, Methods and Constructors in Enums
    • EnumSet
    • EnumMap
    • Strategy Pattern
    • Singleton Pattern
    • Java 8 and Enums
    • JSON Representation of Enum
    • Read More

Java 5 引入枚举类, 详情可参考 官方文档.

啥是枚举类

public enum PizzaStatus {ORDERED,READY, DELIVERED; 
}

Custom Enum Methods

@Data
public class Pizza {private PizzaStatus status;public enum PizzaStatus {ORDERED,READY,DELIVERED;}public boolean isDeliverable() {if (getStatus() == PizzaStatus.READY) {return true;}return false;}
}

Comparing Enum Types Using “==” Operator

the “==” operator provides compile-time and run-time safety.
run-time safety

if(testPz.getStatus().equals(Pizza.PizzaStatus.DELIVERED));null 会报 NullPointerExceptionif(testPz.getStatus() == Pizza.PizzaStatus.DELIVERED);Either value can be null and we won't get a NullPointerException

compile-time safety

PizzaStatus.DELIVERED.equals(PizzaStatus2.ORDERED)    ← 编译不会报错,会返回falsePizzaStatus.DELIVERED == PizzaStatus2.ORDERED    ← 编译会报错

Using Enum Types in Switch Statements

public int getDeliveryTimeInDays() {switch (status) {case ORDERED: return 5;case READY: return 2;case DELIVERED: return 0;}return 0;
}

Fields, Methods and Constructors in Enums

@Data
public class Pizza {public enum PizzaStatus {ORDERED(5) {@Overridepublic boolean isOrdered() {return true;}}, READY(2) {@Overridepublic boolean isReady() {return true;}}, DELIVERED(0) {@Overridepublic boolean isDelivered() {return true;}};private int timeToDelivery;PizzaStatus(int timeToDelivery) {this.timeToDelivery = timeToDelivery;}// 下单public boolean isOrdered() {return false;}// 准备public boolean isReady() {return false;}// 交付public boolean isDelivered() {return false;}public int getTimeToDelivery() {return timeToDelivery;}}private PizzaStatus status;public boolean isDeliverable() {return this.status.isReady();}public void printTimeToDeliver() {System.out.println("Time to delivery is " + this.getStatus().getTimeToDelivery());}
}
    public static void main(String[] args) {Pizza testPz = new Pizza();testPz.setStatus(Pizza.PizzaStatus.READY); // truetestPz.printTimeToDeliver(); // Time to delivery is 2}

EnumSet

与HashSet相比更高效

@Data
public class Pizza {private static EnumSet<PizzaStatus> undeliveredPizzaStatuses = EnumSet.of(PizzaStatus.ORDERED, PizzaStatus.READY);private PizzaStatus status;public enum PizzaStatus {ORDERED(5) {@Overridepublic boolean isOrdered() {return true;}}, READY(2) {@Overridepublic boolean isReady() {return true;}}, DELIVERED(0) {@Overridepublic boolean isDelivered() {return true;}};private int timeToDelivery;PizzaStatus(int timeToDelivery) {this.timeToDelivery = timeToDelivery;}// 下单public boolean isOrdered() {return false;}// 准备public boolean isReady() {return false;}// 交付public boolean isDelivered() {return false;}public int getTimeToDelivery() {return timeToDelivery;}}public boolean isDeliverable() {return this.status.isReady();}public void printTimeToDeliver() {System.out.println("Time to delivery is " + this.getStatus().getTimeToDelivery() + " days");}public static List<Pizza> getAllUndeliveredPizzas(List<Pizza> input) {return input.stream().filter((s) -> undeliveredPizzaStatuses.contains(s.getStatus())).collect(Collectors.toList());}
}
public static void main(String[] args) {List<Pizza> pzList = new ArrayList<>();Pizza pz1 = new Pizza();pz1.setStatus(Pizza.PizzaStatus.DELIVERED);Pizza pz2 = new Pizza();pz2.setStatus(Pizza.PizzaStatus.ORDERED);Pizza pz3 = new Pizza();pz3.setStatus(Pizza.PizzaStatus.ORDERED);Pizza pz4 = new Pizza();pz4.setStatus(Pizza.PizzaStatus.READY);pzList.add(pz1);pzList.add(pz2);pzList.add(pz3);pzList.add(pz4);List<Pizza> undeliveredPzs = Pizza.getAllUndeliveredPizzas(pzList);System.out.println(undeliveredPzs.size()); // 3
}

EnumMap

EnumMap与对应的HashMap相比,它是一个高效而紧凑的实现,内部表示为数组。

public static EnumMap<PizzaStatus, List<Pizza>> groupPizzaByStatus(List<Pizza> pizzaList) {EnumMap<PizzaStatus, List<Pizza>> pzByStatus = new EnumMap<PizzaStatus, List<Pizza>>(PizzaStatus.class);for (Pizza pz : pizzaList) {PizzaStatus status = pz.getStatus();if (pzByStatus.containsKey(status)) {pzByStatus.get(status).add(pz);} else {List<Pizza> newPzList = new ArrayList<Pizza>();newPzList.add(pz);pzByStatus.put(status, newPzList);}}return pzByStatus;
}
public static EnumMap<PizzaStatus, List<Pizza>> groupPizzaByStatus2(List<Pizza> pzList) {EnumMap<PizzaStatus, List<Pizza>> map = pzList.stream().filter(a -> a != null && a.getStatus() != null).collect(Collectors.groupingBy(Pizza::getStatus, () -> new EnumMap<>(PizzaStatus.class), Collectors.toList()));return map;
}
public static Map<PizzaStatus, List<Pizza>> groupPizzaByStatus3(List<Pizza> pizzaList) {Map<PizzaStatus, List<Pizza>> collect = pizzaList.stream().filter(a -> a != null && a.getStatus() != null).collect(Collectors.groupingBy(Pizza::getStatus));return collect;
}
public static void main(String[] args) {List<Pizza> pzList = new ArrayList<>();Pizza pz1 = new Pizza();pz1.setStatus(Pizza.PizzaStatus.DELIVERED);Pizza pz2 = new Pizza();pz2.setStatus(Pizza.PizzaStatus.ORDERED);Pizza pz3 = new Pizza();pz3.setStatus(Pizza.PizzaStatus.ORDERED);Pizza pz4 = new Pizza();pz4.setStatus(Pizza.PizzaStatus.READY);pzList.add(pz1);pzList.add(pz2);pzList.add(pz3);pzList.add(pz4);EnumMap<Pizza.PizzaStatus, List<Pizza>> map = Pizza.groupPizzaByStatus(pzList);System.out.println(map);//{ORDERED=[Pizza(status=ORDERED), Pizza(status=ORDERED)], READY=[Pizza(status=READY)], DELIVERED=[Pizza(status=DELIVERED)]}EnumMap<Pizza.PizzaStatus, List<Pizza>> map2 = Pizza.groupPizzaByStatus2(pzList);System.out.println(map2);// {ORDERED=[Pizza(status=ORDERED), Pizza(status=ORDERED)], READY=[Pizza(status=READY)], DELIVERED=[Pizza(status=DELIVERED)]}Map<Pizza.PizzaStatus, List<Pizza>> map3 = Pizza.groupPizzaByStatus3(pzList);System.out.println(map3);// {READY=[Pizza(status=READY)], ORDERED=[Pizza(status=ORDERED), Pizza(status=ORDERED)], DELIVERED=[Pizza(status=DELIVERED)]}
}

Strategy Pattern

public enum PizzaDeliveryStrategy {EXPRESS {@Overridepublic void deliver(Pizza pz) {System.out.println("Pizza will be delivered in express mode");}}, NORMAL {@Overridepublic void deliver(Pizza pz) {System.out.println("Pizza will be delivered in normal mode");}};public abstract void deliver(Pizza pz);
}

Singleton Pattern

public enum PizzaDeliverySystemConfiguration {INSTANCE;PizzaDeliverySystemConfiguration() {// Initialization configuration which involves overriding defaults like delivery strategy// 初始化配置,包括覆盖默认值,如交付策略}private PizzaDeliveryStrategy deliveryStrategy = PizzaDeliveryStrategy.NORMAL;public static PizzaDeliverySystemConfiguration getInstance() {return INSTANCE;}public PizzaDeliveryStrategy getDeliveryStrategy() {return deliveryStrategy;}
}

Pizza 类里追加如下方法

public void deliver() {if (isDeliverable()) {PizzaDeliverySystemConfiguration.getInstance().getDeliveryStrategy().deliver(this);this.setStatus(PizzaStatus.DELIVERED);}
}
public static void main(String[] args) {Pizza pz = new Pizza();pz.setStatus(Pizza.PizzaStatus.READY);pz.deliver(); // Pizza will be delivered in normal mode System.out.println(pz.getStatus() == Pizza.PizzaStatus.DELIVERED); // true
}

Java 8 and Enums

public static List<Pizza> getAllUndeliveredPizzas(List<Pizza> input) {return input.stream().filter((s) -> undeliveredPizzaStatuses.contains(s.getStatus())).collect(Collectors.toList());
}
public static EnumMap<PizzaStatus, List<Pizza>> groupPizzaByStatus2(List<Pizza> pzList) {EnumMap<PizzaStatus, List<Pizza>> map = pzList.stream().filter(a -> a != null && a.getStatus() != null).collect(Collectors.groupingBy(Pizza::getStatus, () -> new EnumMap<>(PizzaStatus.class), Collectors.toList()));return map;
}
public static Map<PizzaStatus, List<Pizza>> groupPizzaByStatus3(List<Pizza> pizzaList) {Map<PizzaStatus, List<Pizza>> collect = pizzaList.stream().filter(a -> a != null && a.getStatus() != null).collect(Collectors.groupingBy(Pizza::getStatus));return collect;
}

JSON Representation of Enum

-----------------------学习笔记摘自:A Guide to Java Enums

Read More

How To Serialize and Deserialize Enums with Jackson
Check if an Enum Value Exists in Java
Extending Enums in Java
A Guide to EnumMap
Enum in Java

相关文章:

枚举类常见用法,A Guide to Java Enums

目录 啥是枚举类Custom Enum MethodsComparing Enum Types Using “” OperatorUsing Enum Types in Switch StatementsFields, Methods and Constructors in EnumsEnumSetEnumMapStrategy PatternSingleton PatternJava 8 and EnumsJSON Representation of EnumRead More Java…...

Vue Baidu Map--vue引入百度地图

1.安装 npm方式安装 $ npm install vue-baidu-map --save2.局部注册 <template> <div class"map-content" v-if"iscollegeRole"><baidu-map class"bm-view map":ak"mapAK" :scroll-wheel-zoom"true" :cen…...

使用Express部署Vue项目

使用Express部署Vue项目 目录 1. 背景 2. 配置Vue CLI 1.1 安装nodejs 1.2 创建vue-cli 1.3 创建vue项目 1.4 构建vue项目3. 配置Express 2.1 安装express 2.2 创建项目4. 使用express部署vue项目 1&#xff0c;背景 我们想要做一个前后端分离的课程项目&#xff0c;前端…...

344.翻转字符串+387.字符串中的第一个唯一字符

目录 一、翻转字符串 二、字符串中的第一个唯一字符 一、翻转字符串 344. 反转字符串 - 力扣&#xff08;LeetCode&#xff09; class Solution { public:void reverseString(vector<char>& s) {int start0;int end s.size()-1;while(start < end){swap(s[sta…...

安装mmcv

安装MMCV 创建虚拟环境gupao ,并激活nvcc -V 查看cuda版本 打开当前项目文件主页查看环境配置Prerequisites — MMPretrain 1.0.1 documentation 4. 安装合适的torch版本&#xff0c;原来的版本会自动卸载 pip install torch1.13.1cu117 torchvision0.14.1cu117 torch…...

什么是服务网格?

背景&#xff1a; 服务网格这个概念出来很久了&#xff0c;从 2017 年被提出来&#xff0c;到 2018 年正式爆发&#xff0c;很多云厂商和互联网企业都在纷纷向服务网格靠拢。像蚂蚁集团、美团、百度、网易等一线互联 网公司&#xff0c;都有服务网格的落地应用。服务网格是微服…...

8.1作业

文件IO函数实现拷贝文件。子进程先拷贝后半部分&#xff0c;父进程再拷贝前半部分&#xff0c;允许使用sleep函数 #include<stdio.h> #include<string.h> #include<stdlib.h> #include<head.h> int main(int argc, const char *argv[]) {pid_t cpidfo…...

linux-安全技术

文章目录 安全机制墨菲定理信息安全防护的目标安全防护环节常见的安全攻击STRIDE 安全机制 墨菲定理 摘自百度百科 墨菲定律是一种心理学效应&#xff0c;1949年由美国的一名工程师爱德华墨菲&#xff08;Edward A. Murphy&#xff09;提出的&#xff0c;亦称墨菲法则、墨菲…...

如何在免费版 pycharm 中使用 github copilot (chatGPT)?

起因 在 vscode 中使用了 github copilot 以后&#xff0c;感觉这个人工智能还不错。 但 vscode 对于 python 项目调试并不是特别方便&#xff0c;所以想在 Pycharm 中也能使用同一个 github 账号&#xff0c;用上 copilot 的功能。 不需要等待&#xff0c;安装即用&#xff…...

SSD202D-UBOOT-FDT-获取DTB

因为一些需求,我们决定给uboot添加一个功能,在boot阶段识别获取出dtb,然后获取dts参数 DTS引脚是这样设置的 /* * infinity2m-ssc011a-s01a-padmux-display.dtsi- Sigmastar * * Copyright (c) [2019~2020] SigmaStar Technology. * * * This software is licensed under the …...

【Maven】Setting文件分享

<?xml version"1.0" encoding"UTF-8"?><!-- Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding …...

使用requestAnimationFrame 实现倒计时功能js(简单秒数倒计时)

拿一个简单的例子吧 就是获取验证码的倒计时 一般来说就是60秒 首先可能想到就是 setInterval let count 60 setInterval(() > { count --; }, 1000) 还有一种就是 setTImeout 函数的递归调用 let count 60 function coundown() { count --; if(count >…...

jenkins通过sshPut传输文件的时候,报错Permission denied的SftpException

一、背景 使用jenkins的ssh插件传输文件至远程机器的指定目录&#xff0c;php程序打包后&#xff0c;经过zip压缩为oms.zip zip -rq oms.zip ./ -x .git/* -x .env然后我们求md5值 md5sum oms.zip最后执行传输。 09:03:02 Executing command on ssh[116.61.10.149]: mkdir…...

【Python】数据分析+数据挖掘——探索Pandas中的数据筛选

1. 前言 当涉及数据处理和分析时&#xff0c;Pandas是Python编程语言中最强大、灵活且广泛使用的工具之一。Pandas提供了丰富的功能和方法&#xff0c;使得数据的选择、筛选和处理变得简单而高效。在本博客中&#xff0c;我们将重点介绍Pandas中数据筛选的关键知识点&#xff…...

[数据集][目标检测]天牛数据集目标检测数据集VOC格式3050张

数据集格式&#xff1a;Pascal VOC格式(不包含分割路径的txt文件和yolo格式的txt文件&#xff0c;仅仅包含jpg图片和对应的xml) 图片数量(jpg文件个数)&#xff1a;3050 标注数量(xml文件个数)&#xff1a;3050 标注类别数&#xff1a;1 标注类别名称:["longicorn"] …...

python_day16_设计模式

“”“单例模式”“” “”“工厂模式”“” class Person:passclass Worker(Person):passclass Student(Person):passclass Teacher(Person):passclass Factory:def get_person(self, p_type):if p_type w:return Worker()elif p_type s:return Student()else:return Te…...

uniapp开发小程序-实现中间凸起的 tabbar

一、效果展示&#xff1a; 二、代码实现&#xff1a; 1.首先在pages.json文件中进行tabbar的样式和列表配置&#xff0c;代码如下&#xff1a; {"pages": [ //pages数组中第一项表示应用启动页&#xff0c;参考&#xff1a;https://uniapp.dcloud.io/collocation/p…...

Vue引入与Vue拦截原理

1. vue引入 第一种方法&#xff1a;在线引入 <script src"https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> 第二种方法&#xff1a;本地引入 2. Vue拦截原理——例题 el用于绑定id&#xff0c;data用于定义数据如下例题 <!DOCTYPE html&…...

2023年电赛---运动目标控制与自动追踪系统(E题)OpenMV方案

前言 &#xff08;1&#xff09;废话少说&#xff0c;很多人可能无法访问GitHub&#xff0c;所以我直接贴出可能要用的代码。此博客还会进行更新&#xff0c;先贴教程和代码 &#xff08;2&#xff09;视频教程&#xff1a; https://singtown.com/learn/49603/ &#xff08;3&a…...

6G内存运行Llama2-Chinese-7B-chat模型

6G内存运行Llama2-Chinese-7B-chat模型 Llama2-Chinese中文社区 第一步&#xff1a; 从huggingface下载 Llama2-Chinese-7b-Chat-GGML模型放到本地的某一目录。 第二步&#xff1a; 执行python程序 git clone https://github.com/Rayrtfr/llama2-webui.gitcd llama2-web…...

eNSP-Cloud(实现本地电脑与eNSP内设备之间通信)

说明&#xff1a; 想象一下&#xff0c;你正在用eNSP搭建一个虚拟的网络世界&#xff0c;里面有虚拟的路由器、交换机、电脑&#xff08;PC&#xff09;等等。这些设备都在你的电脑里面“运行”&#xff0c;它们之间可以互相通信&#xff0c;就像一个封闭的小王国。 但是&#…...

基于大模型的 UI 自动化系统

基于大模型的 UI 自动化系统 下面是一个完整的 Python 系统,利用大模型实现智能 UI 自动化,结合计算机视觉和自然语言处理技术,实现"看屏操作"的能力。 系统架构设计 #mermaid-svg-2gn2GRvh5WCP2ktF {font-family:"trebuchet ms",verdana,arial,sans-…...

【杂谈】-递归进化:人工智能的自我改进与监管挑战

递归进化&#xff1a;人工智能的自我改进与监管挑战 文章目录 递归进化&#xff1a;人工智能的自我改进与监管挑战1、自我改进型人工智能的崛起2、人工智能如何挑战人类监管&#xff1f;3、确保人工智能受控的策略4、人类在人工智能发展中的角色5、平衡自主性与控制力6、总结与…...

<6>-MySQL表的增删查改

目录 一&#xff0c;create&#xff08;创建表&#xff09; 二&#xff0c;retrieve&#xff08;查询表&#xff09; 1&#xff0c;select列 2&#xff0c;where条件 三&#xff0c;update&#xff08;更新表&#xff09; 四&#xff0c;delete&#xff08;删除表&#xf…...

ssc377d修改flash分区大小

1、flash的分区默认分配16M、 / # df -h Filesystem Size Used Available Use% Mounted on /dev/root 1.9M 1.9M 0 100% / /dev/mtdblock4 3.0M...

CMake基础:构建流程详解

目录 1.CMake构建过程的基本流程 2.CMake构建的具体步骤 2.1.创建构建目录 2.2.使用 CMake 生成构建文件 2.3.编译和构建 2.4.清理构建文件 2.5.重新配置和构建 3.跨平台构建示例 4.工具链与交叉编译 5.CMake构建后的项目结构解析 5.1.CMake构建后的目录结构 5.2.构…...

剑指offer20_链表中环的入口节点

链表中环的入口节点 给定一个链表&#xff0c;若其中包含环&#xff0c;则输出环的入口节点。 若其中不包含环&#xff0c;则输出null。 数据范围 节点 val 值取值范围 [ 1 , 1000 ] [1,1000] [1,1000]。 节点 val 值各不相同。 链表长度 [ 0 , 500 ] [0,500] [0,500]。 …...

数据库分批入库

今天在工作中&#xff0c;遇到一个问题&#xff0c;就是分批查询的时候&#xff0c;由于批次过大导致出现了一些问题&#xff0c;一下是问题描述和解决方案&#xff1a; 示例&#xff1a; // 假设已有数据列表 dataList 和 PreparedStatement pstmt int batchSize 1000; // …...

智能仓储的未来:自动化、AI与数据分析如何重塑物流中心

当仓库学会“思考”&#xff0c;物流的终极形态正在诞生 想象这样的场景&#xff1a; 凌晨3点&#xff0c;某物流中心灯火通明却空无一人。AGV机器人集群根据实时订单动态规划路径&#xff1b;AI视觉系统在0.1秒内扫描包裹信息&#xff1b;数字孪生平台正模拟次日峰值流量压力…...

稳定币的深度剖析与展望

一、引言 在当今数字化浪潮席卷全球的时代&#xff0c;加密货币作为一种新兴的金融现象&#xff0c;正以前所未有的速度改变着我们对传统货币和金融体系的认知。然而&#xff0c;加密货币市场的高度波动性却成为了其广泛应用和普及的一大障碍。在这样的背景下&#xff0c;稳定…...