Java Enum With Constructor Example

Java Enum with Constructor
Many Java developers don't know that Java Enum can have a constructor to pass data while creating Enum constants. This feature allows you to associate related data together. One example of passing arguments to enum Constructor is our TrafficLight Enum where we pass action to each Enum instance e.g. GREEN is associate with go, RED is associated with stop and ORANGE is associated with the slow down. This is really useful because it provides more context and meaning to your code. If you want, you can also provide one or more constructor to your Enum as it also supports constructor overloading like normal Java classes. This is very different from enum you have seen in C or C++, which is just a collection of fixed thing without any OOP power.

How to Randomize a List in Java using Collections.shuffle() Example

The java.util.Collections class provides shuffle() method which can be used to randomize object stored in a List in Java. Since List is an ordered collection and maintains the order on which objects are inserted into it, you may need to randomize elements if you need them in a different order. Collections.shuffle() method uses default randomness to randomize element but you also have an overloaded version of shuffle() to provide an instance of the java.util.Random object, which can be used to randomize elements. Since this method except for fora List, you can also pass it to LinkedList, VectorCopyOnWriteArrayList, and others, which doesn't implement the RandomAccess method.

Java Enum Tutorial - 10 Things Java Devs Should Know about Using Enum

Apart from the Class and Interface, Enumeration type or Enum is another popular type in Java programming language. Enum allows you to represent a fixed number of well-known things in a type-safe manner e.g. days of the week, days of the month, planets in solar system, buttons on remote control, keys on keyboard and suits on playing cards. Before Enum was introduced, prior to Java 1.5, integer and string constants are used to represent the fixed number of things, known as enum int pattern and enum string pattern as described in classic Effective Java by none other than Joshua Bloch. Though they served the purpose, they had some major drawbacks which resulted in poor quality code.