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

科研人必备:用浏览器插件给IEEEXplore做个‘小手术’,告别20秒加载

科研效率革命&#xff1a;用浏览器插件精准优化IEEEXplore访问体验 每次打开IEEEXplore文献库&#xff0c;那个转不停的加载图标是否让你焦躁不安&#xff1f;作为每天要与学术数据库打交道的科研工作者&#xff0c;20秒的等待时间足以打断思考流&#xff0c;降低工作效率。这背…...

S2-Pro企业级监控告警集成:与Prometheus和Grafana的实战

S2-Pro企业级监控告警集成&#xff1a;与Prometheus和Grafana的实战 1. 为什么企业级AI服务需要监控告警 AI服务在生产环境运行时&#xff0c;就像一辆24小时行驶的汽车&#xff0c;需要仪表盘来显示各项关键指标。想象一下&#xff0c;如果你开车时看不到油量表、水温计和速…...

Translategemma-27b-it与OCR结合:图片翻译完整流程

Translategemma-27b-it与OCR结合&#xff1a;图片翻译完整流程 1. 引言 想象一下这样的场景&#xff1a;你在异国旅行时看到一份精美的菜单&#xff0c;却因为语言障碍而不知道点什么&#xff1b;或者在研究国外产品时&#xff0c;标签上的说明文字完全看不懂。传统的翻译工具…...

SEO自动化工具如何提高网站排名_SEO自动化工具如何进行数据报告

<h2>SEO自动化工具如何提高网站排名</h2> <p>在当今互联网时代&#xff0c;网站的排名直接关系到其流量和业务增长。SEO自动化工具如何在提高网站排名方面发挥作用呢&#xff1f;本文将从多个角度展开讨论&#xff0c;帮助你理解这些工具如何提升网站在搜索引…...

实战-EdgeBoard赛事卡:从零部署飞桨模型到智能车竞赛

1. EdgeBoard赛事卡开箱与环境准备 第一次拿到EdgeBoard赛事专用卡时&#xff0c;这块巴掌大的小盒子让我有点怀疑——这么小的板子真能跑动智能车竞赛需要的视觉模型吗&#xff1f;拆开包装后发现&#xff0c;除了板卡本体&#xff0c;配件只有一根Type-C线&#xff0c;确实符…...

Mojo加速Python科学计算:如何在72小时内将AI推理速度提升8.6倍(附完整可运行代码)

第一章&#xff1a;Mojo与Python混合编程概述Mojo 是一种为 AI 系统量身打造的现代系统编程语言&#xff0c;兼具 Python 的易用性与 C/C 的执行效率。它原生兼容 Python 生态&#xff0c;允许开发者在同一个项目中无缝调用 Python 模块、复用现有 NumPy/Torch 代码&#xff0c…...

GLM-Image技术验证:长宽比对构图影响实测数据

GLM-Image技术验证&#xff1a;长宽比对构图影响实测数据 1. 项目背景介绍 GLM-Image是由智谱AI开发的先进文本到图像生成模型&#xff0c;提供了一个美观易用的Web交互界面。这个界面基于Gradio构建&#xff0c;让用户能够轻松使用GLM-Image模型生成高质量的AI图像。 在实际…...

基于Xinference-v1.17.1的嵌入式Linux开发指南

基于Xinference-v1.17.1的嵌入式Linux开发指南 1. 引言 嵌入式设备上的AI推理一直是个技术挑战&#xff0c;特别是在资源受限的环境中部署大模型。Xinference-v1.17.1作为一个开源推理框架&#xff0c;为嵌入式Linux系统提供了轻量级的AI模型部署方案。无论你是想在树莓派上运…...

Splitting.js创意指南:让网页文字动起来的实用技巧

Splitting.js创意指南&#xff1a;让网页文字动起来的实用技巧 【免费下载链接】Splitting JavaScript microlibrary to split an element by words, characters, children and more, populated with CSS variables! 项目地址: https://gitcode.com/gh_mirrors/sp/Splitting …...

嵌入式系统模块化设计:内聚与耦合实战指南

1. 嵌入式模块设计的核心原则在嵌入式系统开发中&#xff0c;模块化设计质量直接影响着整个系统的生命周期成本。我经历过多个嵌入式项目后发现&#xff0c;那些后期维护成本高昂的系统&#xff0c;往往都存在模块边界模糊、依赖混乱的问题。模块化不是简单的代码分割&#xff…...