当前位置: 首页 > 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…...

React 第五十五节 Router 中 useAsyncError的使用详解

前言 useAsyncError 是 React Router v6.4 引入的一个钩子&#xff0c;用于处理异步操作&#xff08;如数据加载&#xff09;中的错误。下面我将详细解释其用途并提供代码示例。 一、useAsyncError 用途 处理异步错误&#xff1a;捕获在 loader 或 action 中发生的异步错误替…...

安宝特方案丨XRSOP人员作业标准化管理平台:AR智慧点检验收套件

在选煤厂、化工厂、钢铁厂等过程生产型企业&#xff0c;其生产设备的运行效率和非计划停机对工业制造效益有较大影响。 随着企业自动化和智能化建设的推进&#xff0c;需提前预防假检、错检、漏检&#xff0c;推动智慧生产运维系统数据的流动和现场赋能应用。同时&#xff0c;…...

定时器任务——若依源码分析

分析util包下面的工具类schedule utils&#xff1a; ScheduleUtils 是若依中用于与 Quartz 框架交互的工具类&#xff0c;封装了定时任务的 创建、更新、暂停、删除等核心逻辑。 createScheduleJob createScheduleJob 用于将任务注册到 Quartz&#xff0c;先构建任务的 JobD…...

MMaDA: Multimodal Large Diffusion Language Models

CODE &#xff1a; https://github.com/Gen-Verse/MMaDA Abstract 我们介绍了一种新型的多模态扩散基础模型MMaDA&#xff0c;它被设计用于在文本推理、多模态理解和文本到图像生成等不同领域实现卓越的性能。该方法的特点是三个关键创新:(i) MMaDA采用统一的扩散架构&#xf…...

DIY|Mac 搭建 ESP-IDF 开发环境及编译小智 AI

前一阵子在百度 AI 开发者大会上&#xff0c;看到基于小智 AI DIY 玩具的演示&#xff0c;感觉有点意思&#xff0c;想着自己也来试试。 如果只是想烧录现成的固件&#xff0c;乐鑫官方除了提供了 Windows 版本的 Flash 下载工具 之外&#xff0c;还提供了基于网页版的 ESP LA…...

python如何将word的doc另存为docx

将 DOCX 文件另存为 DOCX 格式&#xff08;Python 实现&#xff09; 在 Python 中&#xff0c;你可以使用 python-docx 库来操作 Word 文档。不过需要注意的是&#xff0c;.doc 是旧的 Word 格式&#xff0c;而 .docx 是新的基于 XML 的格式。python-docx 只能处理 .docx 格式…...

相机从app启动流程

一、流程框架图 二、具体流程分析 1、得到cameralist和对应的静态信息 目录如下: 重点代码分析: 启动相机前,先要通过getCameraIdList获取camera的个数以及id,然后可以通过getCameraCharacteristics获取对应id camera的capabilities(静态信息)进行一些openCamera前的…...

解决本地部署 SmolVLM2 大语言模型运行 flash-attn 报错

出现的问题 安装 flash-attn 会一直卡在 build 那一步或者运行报错 解决办法 是因为你安装的 flash-attn 版本没有对应上&#xff0c;所以报错&#xff0c;到 https://github.com/Dao-AILab/flash-attention/releases 下载对应版本&#xff0c;cu、torch、cp 的版本一定要对…...

SpringTask-03.入门案例

一.入门案例 启动类&#xff1a; package com.sky;import lombok.extern.slf4j.Slf4j; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cache.annotation.EnableCach…...

【网络安全】开源系统getshell漏洞挖掘

审计过程&#xff1a; 在入口文件admin/index.php中&#xff1a; 用户可以通过m,c,a等参数控制加载的文件和方法&#xff0c;在app/system/entrance.php中存在重点代码&#xff1a; 当M_TYPE system并且M_MODULE include时&#xff0c;会设置常量PATH_OWN_FILE为PATH_APP.M_T…...