Friday, March 4, 2016

Java Enum



https://www.novixys.com/blog/java-enum-examples/
https://stackoverflow.com/questions/28332924/case-insensitive-matching-of-a-string-to-a-java-enum
To do a case-insensitive matching, one can write a custom method inside the Day enum, e.g.
public static Day lookup(String day) {
  for (Day d : Day.values()) {
    if (d.name().equalsIgnoreCase(day)) {
      return type;
    }
  }
  return null;
}


https://deepeshdarshan.wordpress.com/2012/11/14/java-enum-and-abstract-methods/
An enum is a different type of class. The Java Language Specification says “There are two kinds of class declarations: normal class declarations and enumdeclarations. The body of an enum type may contain enum constants. An enum constant defines an instance of the enum type”.
An enum type is a subclass of java.Lang.Enum. An enum cannot extend anything else, but still it can implement other interfaces. Public or protected modifiers can only be used with a top-level enum declaration, but all access modifiers can be used with nested enum declarations. Also an enum type provides final methods like name, compareTo, hashCode etc. We can also use as well as override toString() method in an enum.


https://dzone.com/articles/java-holiday-calendar-2016-day-19-speed-up-your-en
Then it turns out Java will generate an equivalent to the following under the hood:
public static Car[] values() {
    return (Car[])$VALUES.clone();
}

This means each time we are calling values(), we are creating a copy of the internal VALUES array. The reason for this is that an array cannot be protected from being overwritten by user code. Thus, a new copy must be provided for each call to guarantee state integrity. The JVM can mitigate the problem under certain circumstances, but if we want to be absolutely sure no objects are created, we must implement our own equivalent to values(). This can be done like this:
public enum Car {
    TESLA, VOLVO, TOYOTA;
    private static final List<Car> VALUE_LIST = Stream.of(values())
            .collect(collectingAndThen(toList(), Collections::tstrea));
    public static List<Car> valuesAsList() {
        return VALUE_LIST;
    }
}

Note that the internal VALUE_LIST is unmodifiable and that this is important, or else we cannot expose it directly via the valuesAsList() method.
Now we can use our modified Enum like this with no performance overhead:
Car.valuesAsList().forEach(System.out::println);
http://stackoverflow.com/questions/5262096/how-do-i-get-the-value-of-an-enum-if-i-dont-know-the-class-at-compile-time
http://stackoverflow.com/questions/26357132/generic-enum-valueof-method-enum-class-in-parameter-and-return-enum-item
Why implement your own, when you can use Java's own implementation for this?
 YourEnum yourEnum = Enum.valueOf(YourEnum.class, value);
Your method then becomes:
private static <E extends Enum<E>> E getEnum(Class<E> enumClass, String name){
    try {
        return Enum.valueOf(enumClass, name);
    } catch(IllegalArgumentException e) {
        return null;
    }
}
and you can call it with:
getEnum(Enum1.class, "A")

http://tutorials.jenkov.com/java/enums.html
public enum Level {
    HIGH,
    MEDIUM,
    LOW
}

You can obtain an array of all the possible values of a Java enum type by calling its static values()method. All enum types get a static values() method automatically by the Java compiler. Here is an example of iterating all values of an enum:
for (Level level : Level.values()) {
    System.out.println(level);
}
Running this Java code would print out all the enum values. Here is the output:
HIGH
MEDIUM
LOW


Java enums extend the java.lang.Enum class implicitly, so your enum types cannot extend another class.


If a Java enum contains fields and methods, the definition of fields and methods must always come afterthe list of constants in the enum. Additionally, the list of enum constants must be terminated by a semicolon;

You can add fields to a Java enum. Thus, each constant enum value gets these fields. The field values must be supplied to the constructor of the enum when defining the constants. Here is an example:
public enum Level {
    HIGH  (3),  //calls constructor with value 3
    MEDIUM(2),  //calls constructor with value 2
    LOW   (1)   //calls constructor with value 1
    ; // semicolon needed when fields / methods follow


    private final int levelCode;

    private Level(int levelCode) {
        this.levelCode = levelCode;
    }
}
http://www.hankcs.com/program/java/enum-java-examples-of-dynamic-modification.html

<T extends Comparable<? super T>> void sort( List<T> list ) { ... }
Comparable<? super T> is the set of instantiations of Comparable on T and all of its superclasses. A Comparable<T> suffices and, at the other end, so does a Comparable<Object>. What this means in English is that the elements must be comparable to their own type or some supertype of their own type. This is sufficient to ensure that the elements can all be compared to one another, but not as restrictive as saying that they must all implement the compareTo() method themselves. Some of the elements may inherit the Comparable interface from a parent class that knows how to compare only to a supertype of T, and that is exactly what is allowed here.


The type A may not subclass Enum explicitly.
public abstract class Enum<E extends Enum<E>>
        implements Comparable<E>, Serializable
private void readObject(ObjectInputStream in) throws IOException,
    ClassNotFoundException {
    throw new InvalidObjectException("can't deserialize enum");
}

private void readObjectNoData() throws ObjectStreamException {
    throw new InvalidObjectException("can't deserialize enum");
}      

This class is the common superclass of all enumerated types. It is not itself an enum type, however, and a Java compiler does not allow other classes to extend it. Subclasses of Enum may be only created with enum declarations. Enum is a generic type, and the type variable E represents the concrete enumerated type that actually extends Enum. This type variable exists so that Enum can implement Comparable<E>.

Most users of enumerated constants will use toString( ) instead of name( ). The implementation of toString( ) defined by Enum returns the same value as name( ). The toString( ) method is not final, however, and it can be overridden in enum declarations.

Enum doesn't support clone
protected final Object clone() throws CloneNotSupportedException {
    throw new CloneNotSupportedException();
}

public final boolean equals(Object other) {
    return this==other;
}
public static <T extends Enum<T>> T valueOf(Class<T> enumType, String name)

Labels

Review (572) System Design (334) System Design - Review (198) Java (189) Coding (75) Interview-System Design (65) Interview (63) Book Notes (59) Coding - Review (59) to-do (45) Linux (43) Knowledge (39) Interview-Java (35) Knowledge - Review (32) Database (31) Design Patterns (31) Big Data (29) Product Architecture (28) MultiThread (27) Soft Skills (27) Concurrency (26) Cracking Code Interview (26) Miscs (25) Distributed (24) OOD Design (24) Google (23) Career (22) Interview - Review (21) Java - Code (21) Operating System (21) Interview Q&A (20) System Design - Practice (20) Tips (19) Algorithm (17) Company - Facebook (17) Security (17) How to Ace Interview (16) Brain Teaser (14) Linux - Shell (14) Redis (14) Testing (14) Tools (14) Code Quality (13) Search (13) Spark (13) Spring (13) Company - LinkedIn (12) How to (12) Interview-Database (12) Interview-Operating System (12) Solr (12) Architecture Principles (11) Resource (10) Amazon (9) Cache (9) Git (9) Interview - MultiThread (9) Scalability (9) Trouble Shooting (9) Web Dev (9) Architecture Model (8) Better Programmer (8) Cassandra (8) Company - Uber (8) Java67 (8) Math (8) OO Design principles (8) SOLID (8) Design (7) Interview Corner (7) JVM (7) Java Basics (7) Kafka (7) Mac (7) Machine Learning (7) NoSQL (7) C++ (6) Chrome (6) File System (6) Highscalability (6) How to Better (6) Network (6) Restful (6) CareerCup (5) Code Review (5) Hash (5) How to Interview (5) JDK Source Code (5) JavaScript (5) Leetcode (5) Must Known (5) Python (5)

Popular Posts