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

利用最小二乘法找圆心和半径

#include <iostream> #include <vector> #include <cmath> #include <Eigen/Dense> // 需安装Eigen库用于矩阵运算 // 定义点结构 struct Point { double x, y; Point(double x_, double y_) : x(x_), y(y_) {} }; // 最小二乘法求圆心和半径 …...

LBE-LEX系列工业语音播放器|预警播报器|喇叭蜂鸣器的上位机配置操作说明

LBE-LEX系列工业语音播放器|预警播报器|喇叭蜂鸣器专为工业环境精心打造&#xff0c;完美适配AGV和无人叉车。同时&#xff0c;集成以太网与语音合成技术&#xff0c;为各类高级系统&#xff08;如MES、调度系统、库位管理、立库等&#xff09;提供高效便捷的语音交互体验。 L…...

(LeetCode 每日一题) 3442. 奇偶频次间的最大差值 I (哈希、字符串)

题目&#xff1a;3442. 奇偶频次间的最大差值 I 思路 &#xff1a;哈希&#xff0c;时间复杂度0(n)。 用哈希表来记录每个字符串中字符的分布情况&#xff0c;哈希表这里用数组即可实现。 C版本&#xff1a; class Solution { public:int maxDifference(string s) {int a[26]…...

以下是对华为 HarmonyOS NETX 5属性动画(ArkTS)文档的结构化整理,通过层级标题、表格和代码块提升可读性:

一、属性动画概述NETX 作用&#xff1a;实现组件通用属性的渐变过渡效果&#xff0c;提升用户体验。支持属性&#xff1a;width、height、backgroundColor、opacity、scale、rotate、translate等。注意事项&#xff1a; 布局类属性&#xff08;如宽高&#xff09;变化时&#…...

Python:操作 Excel 折叠

💖亲爱的技术爱好者们,热烈欢迎来到 Kant2048 的博客!我是 Thomas Kant,很开心能在CSDN上与你们相遇~💖 本博客的精华专栏: 【自动化测试】 【测试经验】 【人工智能】 【Python】 Python 操作 Excel 系列 读取单元格数据按行写入设置行高和列宽自动调整行高和列宽水平…...

深入理解JavaScript设计模式之单例模式

目录 什么是单例模式为什么需要单例模式常见应用场景包括 单例模式实现透明单例模式实现不透明单例模式用代理实现单例模式javaScript中的单例模式使用命名空间使用闭包封装私有变量 惰性单例通用的惰性单例 结语 什么是单例模式 单例模式&#xff08;Singleton Pattern&#…...

【CSS position 属性】static、relative、fixed、absolute 、sticky详细介绍,多层嵌套定位示例

文章目录 ★ position 的五种类型及基本用法 ★ 一、position 属性概述 二、position 的五种类型详解(初学者版) 1. static(默认值) 2. relative(相对定位) 3. absolute(绝对定位) 4. fixed(固定定位) 5. sticky(粘性定位) 三、定位元素的层级关系(z-i…...

Qwen3-Embedding-0.6B深度解析:多语言语义检索的轻量级利器

第一章 引言&#xff1a;语义表示的新时代挑战与Qwen3的破局之路 1.1 文本嵌入的核心价值与技术演进 在人工智能领域&#xff0c;文本嵌入技术如同连接自然语言与机器理解的“神经突触”——它将人类语言转化为计算机可计算的语义向量&#xff0c;支撑着搜索引擎、推荐系统、…...

Cinnamon修改面板小工具图标

Cinnamon开始菜单-CSDN博客 设置模块都是做好的&#xff0c;比GNOME简单得多&#xff01; 在 applet.js 里增加 const Settings imports.ui.settings;this.settings new Settings.AppletSettings(this, HTYMenusonichy, instance_id); this.settings.bind(menu-icon, menu…...

鸿蒙中用HarmonyOS SDK应用服务 HarmonyOS5开发一个医院查看报告小程序

一、开发环境准备 ​​工具安装​​&#xff1a; 下载安装DevEco Studio 4.0&#xff08;支持HarmonyOS 5&#xff09;配置HarmonyOS SDK 5.0确保Node.js版本≥14 ​​项目初始化​​&#xff1a; ohpm init harmony/hospital-report-app 二、核心功能模块实现 1. 报告列表…...