Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
Today I was browsing through some questions on this site and I found a mention of an enum being used in singleton pattern about purported thread safety benefits to such solution. I have never used enums and I have been programing in Java for more than couple a years now. And apparently they changed a lot. Now they even do full blown support of OOP within themselves. Now why and what for shoul...
Are there any best-practice guidelines on when to use case classes vs extending Enumeration in Scala? They seem to offer some of the same benefits.
When working with variables/parameters that can only take a finite number of values, I try to always use Java's enum, as in public enum BonusType { MONTHLY, YEARLY, ONE_OFF } As long as I stay inside my code, that works fine. However, I often need to interface with other code that uses plain int (or String) values for the same purpose, or I need to read/write from/to a database where the ...
I declare an enum as : enum Sex {MALE,FEMALE}; And then, iterate enum as shown below : for(Sex v : Sex.values()){ System.out.println(" values :"+ v); } I checked up Java API but can't find values() method ? Curious where does this method come from? API link : http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Enum.html
An Enum in Java implements the Comparable interface. It would have been nice to override Comparable's compareTo method, but here it's marked as final. The default natural order on Enum's compareTo is the listed order. Does anyone know why a Java Enum has this restriction?
The ordinal() method returns the ordinal of an enum instance. How can I set the ordinal for an enum?
I have a problem in Java using Enums. I have read the documentation about assigning value parameters to Enums. But, my question is what about multiple values, is it possible? This what I would like to achieve: I have an Enum for languages. Each language is represented by its name and some shorter aliases (not always, and not always the same number of aliases) Here is an example: public enum ...
I was trying to understand how Java enum really works and I have come to the conclusion that is very similar to a normal Java class that has it's constructor declared private. I have just come to this conclusion and it isn't based on much thinking, but Id like to know whether I miss anything. So below is an implementation of a simple Java enum and an equivalent Java class. public enum Direct...
I'm currently creating integer constants in the following manner. public class Constants { public static int SIGN_CREATE=0; public static int SIGN_CREATE=1; public static int HOME_SCREEN=2; public static int REGISTER_SCREEN=3; } When i try to do this in enum manner public enum PAGE{SIGN_CREATE,SIGN_CREATE,HOME_SCREEN,REGISTER_SCREEN} and When i used PAGE.SIGN_CREATE it should return 1;
In Java, I'd like to be able to define marker interfaces, that forced implementations to provide static methods. For example, for simple text-serialization/deserialization I'd like to be able to define an interface that looked something like this: public interface TextTransformable<T>{ public static T fromText(String text); public String toText(); Since interfaces in Java can't c...
What's the easiest and/or shortest way possible to get the names of enum elements as an array of Strings? What I mean by this is that if, for example, I had the following enum: public enum State { NEW, RUNNABLE, BLOCKED, WAITING, TIMED_WAITING, TERMINATED; public static String[] names() { // ... } } the names() method would return an array analog to ...
Given the following java enum: public enum AgeRange { A18TO23 { public String toString() { return "18 - 23"; } }, A24TO29 { public String toString() { return "24 - 29"; } }, A30TO35 { public String toString() { return "30 - 35"; } }, } Is there any way to convert a string value of "18 - 23" to the...
Is there a way to set up such enum values via Spring IoC at construction time? What I would like to do is to inject, at class load time, values that are hard-coded in the code snippet below: public enum Car { NANO ("Very Cheap", "India"), MERCEDES ("Expensive", "Germany"), FERRARI ("Very Expensive", "Italy"); public final String cost; public final Stri...
I realise Java 8 is still in Beta but this one struck me as odd: public class Fields<C extends Enum<C>> { public Fields(Set<C> columns) { // A sample column used to find the universe of the enum of Columns. C sampleCol = columns.iterator().next(); // Java 8 needs a cast here. Set<C> allColumns = EnumSet.allOf((/*Class<C>)*/ sam...
Is there a way to check if an enum value is 'greater/equal' to another value? I want to check if an error level is 'error or above'.
While reading Effective Java I came across the suggestion to "use enums instead of int constants". In a current project I am doing something similar to that below: int COL_NAME = 0; int COL_SURNAME = 1; table[COL_NAME] = "JONES" How would I use enums instead to achieve this? Due to the interface I'm forced to use, I must use an int for my index. The example above is just an example. I'm ac...
I've noticed that the following snippet... @Override public boolean equals(Object otherObject) { ... } ...is not allowed for an Enum, since the method equals(Object x) is defined as final in Enum. Why is this so? I cannot think of any use case which would require overriding equals(Object) for Enum. I'm just curious to know the reasoning behind this behavior.
How do I get the name of a Java Enum type given its value? I have written code which works for a particular Enum type, can I make it more generic? The enum type: public enum Category { APPLE("3"), ORANGE("1"), GRAPE("GRAPE"), BANANA("Banana"); private final String identifier; /** * Constructor. * * @param identifier * - identfier. */ priv...
Suppose you have public enum Week { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY } How can one get int representing that Sunday is 0, Wednesday is 3 etc?
Good day! I want to convert this sample C# code into a java code: public enum myEnum { ONE = "one", TWO = "two", }; because I want to change this constant class into enum public final class TestConstants { public static String ONE = "one"; public static String TWO= "two"; } Thank you
After reading the documentation of String java.lang.Enum.name() I am not sure I understand when to use name() and when to use toString(). Returns the name of this enum constant, exactly as declared in its enum declaration. Most programmers should use the toString method in preference to this one, as the toString method may return a more user-friendly name. This method is designed primarily ...
  /*
   * Copyright (c) 2003, 2007, Oracle and/or its affiliates. All rights reserved.
   * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   *
   * This code is free software; you can redistribute it and/or modify it
   * under the terms of the GNU General Public License version 2 only, as
   * published by the Free Software Foundation.  Oracle designates this
   * particular file as subject to the "Classpath" exception as provided
   * by Oracle in the LICENSE file that accompanied this code.
  *
  * This code is distributed in the hope that it will be useful, but WITHOUT
  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  * version 2 for more details (a copy is included in the LICENSE file that
  * accompanied this code).
  *
  * You should have received a copy of the GNU General Public License version
  * 2 along with this work; if not, write to the Free Software Foundation,
  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  *
  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  * or visit www.oracle.com if you need additional information or have any
  * questions.
  */
 
 package java.lang;
 
This is the common base class of all Java language enumeration types.

Author(s):
Josh Bloch
Neal Gafter
Since:
1.5
See also:
Class.getEnumConstants()
 
 public abstract class Enum<E extends Enum<E>>
         implements Comparable<E>, Serializable {
    
The name of this enum constant, as declared in the enum declaration. Most programmers should use the toString() method rather than accessing this field.
 
     private final String name;

    
Returns the name of this enum constant, exactly as declared in its enum declaration. Most programmers should use the toString() method in preference to this one, as the toString method may return a more user-friendly name. This method is designed primarily for use in specialized situations where correctness depends on getting the exact name, which will not vary from release to release.

Returns:
the name of this enum constant
 
     public final String name() {
         return ;
     }

    
The ordinal of this enumeration constant (its position in the enum declaration, where the initial constant is assigned an ordinal of zero). Most programmers will have no use for this field. It is designed for use by sophisticated enum-based data structures, such as java.util.EnumSet and java.util.EnumMap.
 
     private final int ordinal;

    
Returns the ordinal of this enumeration constant (its position in its enum declaration, where the initial constant is assigned an ordinal of zero). Most programmers will have no use for this method. It is designed for use by sophisticated enum-based data structures, such as java.util.EnumSet and java.util.EnumMap.

Returns:
the ordinal of this enumeration constant
 
     public final int ordinal() {
         return ;
     }

    
Sole constructor. Programmers cannot invoke this constructor. It is for use by code emitted by the compiler in response to enum type declarations.

Parameters:
name - The name of this enum constant, which is the identifier used to declare it.
ordinal - The ordinal of this enumeration constant (its position in the enum declaration, where the initial constant is assigned an ordinal of zero).
    protected Enum(String nameint ordinal) {
        this. = name;
        this. = ordinal;
    }

    
Returns the name of this enum constant, as contained in the declaration. This method may be overridden, though it typically isn't necessary or desirable. An enum type should override this method when a more "programmer-friendly" string form exists.

Returns:
the name of this enum constant
    public String toString() {
        return ;
    }

    
Returns true if the specified object is equal to this enum constant.

Parameters:
other the object to be compared for equality with this object.
Returns:
true if the specified object is equal to this enum constant.
    public final boolean equals(Object other) {
        return this==other;
    }

    
Returns a hash code for this enum constant.

Returns:
a hash code for this enum constant.
    public final int hashCode() {
        return super.hashCode();
    }

    
Throws CloneNotSupportedException. This guarantees that enums are never cloned, which is necessary to preserve their "singleton" status.

Returns:
(never returns)
    protected final Object clone() throws CloneNotSupportedException {
        throw new CloneNotSupportedException();
    }

    
Compares this enum with the specified object for order. Returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object. Enum constants are only comparable to other enum constants of the same enum type. The natural order implemented by this method is the order in which the constants are declared.
    public final int compareTo(E o) {
        Enum other = (Enum)o;
        Enum self = this;
        if (self.getClass() != other.getClass() && // optimization
            self.getDeclaringClass() != other.getDeclaringClass())
            throw new ClassCastException();
        return self.ordinal - other.ordinal;
    }

    
Returns the Class object corresponding to this enum constant's enum type. Two enum constants e1 and e2 are of the same enum type if and only if e1.getDeclaringClass() == e2.getDeclaringClass(). (The value returned by this method may differ from the one returned by the Object.getClass() method for enum constants with constant-specific class bodies.)

Returns:
the Class object corresponding to this enum constant's enum type
    public final Class<E> getDeclaringClass() {
        Class clazz = getClass();
        Class zuper = clazz.getSuperclass();
        return (zuper == Enum.class) ? clazz : zuper;
    }

    
Returns the enum constant of the specified enum type with the specified name. The name must match exactly an identifier used to declare an enum constant in this type. (Extraneous whitespace characters are not permitted.)

Parameters:
enumType the Class object of the enum type from which to return a constant
name the name of the constant to return
Returns:
the enum constant of the specified enum type with the specified name
Throws:
IllegalArgumentException if the specified enum type has no constant with the specified name, or the specified class object does not represent an enum type
NullPointerException if enumType or name is null
Since:
1.5
    public static <T extends Enum<T>> T valueOf(Class<T> enumType,
                                                String name) {
        T result = enumType.enumConstantDirectory().get(name);
        if (result != null)
            return result;
        if (name == null)
            throw new NullPointerException("Name is null");
        throw new IllegalArgumentException(
            "No enum const " + enumType +"." + name);
    }

    
enum classes cannot have finalize methods.
    protected final void finalize() { }

    
prevent default deserialization
    private void readObject(ObjectInputStream inthrows IOException,
        ClassNotFoundException {
            throw new InvalidObjectException("can't deserialize enum");
    }
    private void readObjectNoData() throws ObjectStreamException {
            throw new InvalidObjectException("can't deserialize enum");
    }
New to GrepCode? Check out our FAQ X