Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
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...
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?
Today I was browsing through some question on this site and I found mention of enum being used in singleton pattern and that there are some thread safety benefits to such solution. I never used enums and I have been programing in java for more than couple a years now. And apparently they changed a lot and now they even do full blown support of OOP within them selfs. Now why and what for shoul...
Perhap this is a simple basic question Having an enum public enum TK{ ID,GROUP,DATA,FAIL; } Can I get the order number for example ID=0, GROUP=2, DATA=3, FAIL=4 ? This is a way to to that, but a weird and long one! =S public enum TK{ ID(0),GROUP(1),DATA(2),FAIL(3); int num; TK(int n) { this.num=n; } public int g...
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'.
Given the followin enum : public enum Car { NANO ("Very Cheap", "India"), MERCEDES ("Expensive", "Germany"), FERRARI ("Very Expensive", "Italy"); public final String cost; public final String madeIn; Car(String cost, String madeIn) { this.cost= cost; this.madeIn= madeIn; } } Does someone know a...
While using Java's switch case, it excepts only char and int, but I want to provide string cases. How to make this possible?
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 ...
If a Java class implements the Serializable interface but does not have a public clone() method, it is usually possible to create a deep copy like this: class CloneHelper { @SuppressWarnings("unchecked") public static <T extends Serializable> T clone(T obj) { try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = n...
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 ...
Consider this code: public interface Foo extends Comparable<Foo> { ... } public enum FooImpl implements Foo { ... } Due to the restrictions of type erasure, I receive the following error: java.lang.Comparable cannot be inherited with different arguments: <Foo> and <FooImpl> I have the following requirements: FooImpl needs to be an enum, because I need to use it as a d...
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...
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 acheive 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 seem to have faced this problem many times and I wanted to ask the community whether I am just barking up the wrong tree. Basically my question can be distilled down to this: if I have an enum (in Java) for which the values are important, should I be using an enum at all or is there a better way, and if I do use an enum then what is the best way to reverse the lookup? Here's an example. Supp...
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.
If I have a string like: String myColor = "Color.RED"; How do I get that to work in: graphics.setColor(myColor); I guess I'm asking how do I pass a variable object name to a function. I've tried a bunch of stuff and can not get it working.
Every Java enumeration has a static values() method can be used like this for (MyEnum enum : MyEnum.values()) { // Do something with enum } However, I cannot figure out where this method is defined. There's no mention of it in the Javadoc and it doesn't appear anywhere in the source file.
I'd like to create a generic enum-based mapper for IBatis. I'm doing this with the below code. This does have compile time errors, which I don't know how to fix. Maybe my solution is just plain wrong (keep in mind the use of IBatis), in such case please suggest something better. Any help appreciated. What I want to achieve is to define subsequent mappers as: public class XEnumTypeHandler ext...
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;
The ordinal() method can get the ordinal of a enum instance. How can I set the ordinal for a enum ?
I have the following enum: public enum Status implements StringEnum{ ONLINE("on"),OFFLINE("off"); private String status = null; private Status(String status) { this.status = status; } public String toString() { return this.status; } public static Status find(String value) { for(Status status : Status.values()) { if(status.toString().equals(value)) { return status; ...
  /*
   * Copyright 2003-2007 Sun Microsystems, Inc.  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.  Sun designates this
   * particular file as subject to the "Classpath" exception as provided
   * by Sun 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
  * CA 95054 USA or visit www.sun.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