Cases and possibilities of using Java enums mutes?

综合编程 2018-01-01 阅读原文

I don't know if I'm the only one to know that, but the values of an enum are not implicitly final and can be modified.

enum EnumTest {
    TOTO("TOTO 1"),
    TATA("TATA 2"),
    ;

    private String str;

    private EnumTest(String str) {
      this.str = str;
    }

    @Override
    public String toString() {
      return str;
    }
  }

  public static void main(String[] args) {
    System.out.println(EnumTest.TATA);
    EnumTest.TATA.str = "newVal";
    System.out.println(EnumTest.TATA);
  }

TATA 2
newVal

These values are oftenly initialized at instance creation ( TOTO("TOTO 1")
) but, except myself, I've never seen anyone using the final keyword for enum variables that should be immutable. That's not the point of the question, just wondering if I'm the only one aware of this.

What I'd like to know is if there was any usecase to create mutable enums?

And I'd also like to know the limits of what we can do with enums (good practice or not). I've not tested it, but maybe an enum can be injected with Spring beans? At least it seems we can annotate each instance (@Deprecated works fine for exemple), and also the methods.

One possible usecase would be lazy initialization (calculate some field values when they are first used, if often they are not used at all), or a "normal" mutable singleton object (like a registry or such).

In most cases, though, enum objects should be immutable, and their fields be final.

Hello, buddy!

责编内容by:Hello, buddy!阅读原文】。感谢您的支持!

您可能感兴趣的

Abstraction in Java – Difference between Abstracti... 1. Objective In this Java tutorial , we are going to learn about the concept of Abstraction in Java and different...
Entry number of the rest of the entry How to change the string format of the text between the line number and the history entry in the history output...
《Java从小白到大牛》之第8章 数组 在计算机语言中数组是非常重要的集合类型,大部分计算机语言中数组具有如下三个基本特性: 一致性:数组只能保存相同数据类型元素,元素的数据类型可以是任何相同的数据类型。 有序性:数组中的元素是有序的,通过下标访问。 不可...
java 伪异步通信模型详解 BIO的改进方案 为了改进BIO一线程一连接模型,演进出了一种通过线程池或者消息队列实现1个或者多个线程处理N个客户端的模型,由于它的底层通信机制依然使用同步阻塞I/O,所以被称为“伪异步”。 后端通过一个线程池来处理多个的请求,形...
阿里面试官的分享Java面试中需要准备哪些多线程并发的技术要点... 一、概念 什么是线程 一个线程要执行任务,必须得有线程 一个进程(程序)的所有任务都在线程中执行的 一个线程执行任务是串行的,也就是说一个线程,同一时间内,只能执行一个任务 多线程原理 ...