Equivalent to C Defines / sparse enums

Hi,
I'm looking for a way to implement defines / sparse enums in Labview easily. For example if I use Labview to communicate with a device that has a set of commands, I want to define the possible commands in a central location and if new commands are added or the numbers change or whatever, I want this to be propagated to all places where it is used.
I already searched in the forums a little but didn't find a satisfying solution.
An enum doesn't really do the job if the values are not sequential. One way I could do it is by using a case structure or an array additionally but this means always keeping two places up-to-date. A text ring would be the better solution (though I still miss the possibility to map different names to the same value, which I need in some cases) but the big letdown is that constants of a text ring strict typedef are not updated so it is useless for what I want.
Actually I just want something like
typedef enum
    FOO = 0,
    BAR = 0,
    FOOBAR = 10
} foobar;
or 
#define FOO       0
#define BAR        0
#define FOOBAR 10
which is standard in C but seems unnecessary complicated and not straight-forward in LabView. Is there an elegant and easy solution? If not, are the LabView developers aware of this shortcoming and will it be implemented in future releases?
Thanks,
Tobias

Hi, Tobias,
There are many different ways how to implement this, depends from your needs and architecture.
In some cases just Globals may be useful (they are not always bad).
You can also create SubVIs like containers for your #defines, or using universal Functional Global VI, where these values will be stored - this is most flexible way. See examples:
Andrey.
Attachments:
Defines.zip ‏30 KB

Similar Messages

  • How to define Sparse/dense settings through MAXL script ?

    Hi,
    How to define Sparse/dense settings through MAXL script ?
    By default its taking all dimensions as sparse dimension type. I want to define sparse and dense through MAXLand automate everything.
    Please help me out or advice me work around.
    Thanks,
    Rajendra Prasad Gella.

    you cannot modify sparse/desne settings directly through MAXL.
    The only way you will be able to build/modify/remove dimensions/members through maxl is using rules files.
    So if you are building dimensions using rules files, for a new dimension you can specify dimension properties.
    in rules file options -> dimension build settings -> dimension definition -> Rules file -> dimensions.
    Here you can specify new dimensions and after specifying you can right click and edit properties where you can change various dimension level properties including sparse/dense settings.
    And you knw me well (Krishna from Hyd) and so you can call me on my mobile if you need more info.. lol :)
    - Krish

  • Defining constants/enums with const in JavaScript

    Hi folks,
    I like to define constant enums like the InDesign DOM already provides, e.g.:
    SpecialCharacters.FORCED_LINE_BREAK
    StateTypes.DOWN
    etc.
    I like to define such enums too. The only approach I found was:
    const MY_ENUM = {TOP:"top",DOWN:"down"}
    But this is not write-safe. I can add properties/functions to MY_ENUM as well as change the value of TOP. Thats not desirable.
    Whereas the InDesign DOM enums are readonly. The enum object as well as the value/property. How can I define such type with JavaScript?
    Thanks for your comments
    Cheers Tino

    Alternatively, it is sufficient if you create an output terminal named CO in this case. No need to connect it, of course.
    LabVIEW Champion . Do more with less code and in less time .
    Attachments:
    FormulaNode.gif ‏3 KB

  • Define/access  enum in mbean definition

    In my MBean interface, I defined a typesafe enum that defines states of the system that the mbean is managing.
    Here is my mbean definition:
    public interface TestMBean
        public Status getStatus();
        public enum Status { NOT_STARTED,  STARTED, SUCCESS, FAILED }
    }Is it a good idea to define a enum? If it is not, should I simply use Strings in the status? What is the right way?

    It's really a matter of taste, but I often prefer discrete potential enum values over wide-open String values for things like status. Enums are particularly useful with MXBeans as described in [this blog entry|http://marxsoftware.blogspot.com/2008/06/jmx-mxbean.html].

  • Creating sparse enums in CVI for LabVIEW

    LabVIEW, for some reason, does not support creating or editing sparse enums.
    NI, however, describes a process to import sparse enums created in CVI.
    I want to try to hack this and see if I can create an editor for these, but I don't have CVI, so I was hoping someone could create a couple of these sparse enums and upload them. I'm not sure if this matters, but I have access to LV 7.0 and 7.1, so I'd appreciate something in parallel versions.
    Examples:
    [value, label
    1, one
    4, four
    6, six
    2, two
    [value, label
    6, apple
    24, orange
    18, pear
    27, peach
    0, grape
    Thank you.
    Try to take over the world!

    I'm not sure how this was posted to the LV board, as I made sure the target was the CVI board before I posted, but I guess I will just have to post it again.
    Try to take over the world!

  • Calculating Enum Values that aren't powers of two using the current enumeration values

    // SortedSet is not necessary but it has convenient Min and Max properties.
    SortedSet<MyEnum> enumValues = new SortedSet<MyEnum>();
    foreach (MyEnum e in Enum.GetValues(typeof(MyEnum)))
    enumValues.Add(e);
    // enumValues.Max * 2 to check all combinations including the last flag.
    for (int i = (int)enumValues.Min + 1; i < (int)enumValues.Max * 2; i++)
    MyEnum currentlyChecked = (MyEnum)i;
    // if there's no equivalent of i defined in MyEnum
    if (!enumValues.Contains(currentlyChecked))
    string representation = "";
    // Iterate over all MyEnum flags which underlying value is lower than i
    // and add those flags which are contained in (MyEnum)i to the string representation
    // of the value missing from the MyEnum enumeration.
    foreach (MyEnum lowerValue in enumValues.Where(e => (int)e < i))
    if (currentlyChecked.HasFlag(lowerValue))
    representation += lowerValue.ToString();
    if (String.IsNullOrEmpty(representation))
    representation = "[MISSING FLAG]";
    if (representation.Contains("None") | representation.Contains("Undefined"))
    representation = representation.Replace("Undefined", "");
    representation = representation.Replace("None", "");
    Console.WriteLine("Missing value: {0} - {1}", i, representation);
    I have the above code, which works great when The type of the Enumeration is known. However, the actual code is loading the Enumerations through reflection and placing the values and names into a Dictionary <int, string>. I need to be able to use the
    above code with my dictionary to achieve the same result, however  when I try to modify the above code for the dictionary, I run into a problem.
    The Enum that it is scanning looks like this:
    [Flags]
    public enum Method
    Undefined = 0,
    Site = 1,
    Manual = 2,
    API = 4
    and the output should be
    3: SiteManual - This works fine
    5: PortalAPI
    6: ManualAPI
    7: SiteManualAPI
    However, the output it is giving me is
    3: SiteManual
    5: SiteManualAPI
    6: SiteManualAPI
    7: SiteManualAPI
    How do I adapt the above code so I can calculate the proper values without having Enum type, since I can't seem to create the sorted set from the reflection type.

    I guess you want something like this:
    int someValue = 5;
    string result = ((int[])Enum.GetValues(typeof(Method)))
    .Aggregate("", (a, s) =>
    if ((someValue & s) != 0)
    a += Enum.GetName(typeof(Method), s) + " ";
    return a;
    // someValue=5 -> Site API
    // someValue=6 -> Manual API
    // someValue=7 -> Site Manual API
    // someValue=13 -> Site API

  • Activex enums and disabled methods

    I am relatively new to using Labview for accessing COM objects. I am trying to use Labview to access an SDK library for controlling a USB ultrasound machine. I am having a couple of problems that I am not sure if I can get around and would appreciate any help.
    Firstly, I am having accessing tagged enums which are inputs to methods. This works for some inputs, where the enums are sequential (SCAN_STATE_STOP = 0, SCAN_STATE_ACQUIRE = 1, SCAN_STATE_FREEZE = 2,SCAN_STATE_RUN = 3). When I right click on the input and right click, the appropriate enum list shows. But this does not work for others that are not sequential (e.g. SCAN_MODE_UNKNOWN = 0,SCAN_MODE_B = 1,SCAN_MODE_M = 2,SCAN_MODE_PW = 4,SCAN_MODE_BPW = 7 etc). Is there a way of being able to access these? By just defining the integer value, I seem to be getting errors in some methods (but not all). 
    I am also having a problem in that one of the methods of the a specfic class is greyed out and disabled (GetControlObj). The input for this method is 'System.Guid@ riidCtrl', System.UInt32 ScanMode and System.UInt32 streamId. I suspect that the problem is that Labview cannot interfacece GUID object that needs to be input. Is this correct? Is there any way around this?
    Regards,
    Glen 

    Litch09 wrote:
    I am sorry if my lingo is not up to speed, I have no formal programming training!
    Neither have I, and that's never stopped me... (My "formal training" is as an electrical engineer! )
    What you are seeing is behavior by design. Whether or not it's correct is debatable. LabVIEW enums are always consecutive. If you want to use a dropdown that has a text label with non-consecutive values then you can make a ring constant. Unfortunately, you have to do this manually. Basically, you're wanting to create a "sparse enum".If you do search for "spase enum" you'll find some information. A while ago JeanPierre wrote a tool to create an enum typedef and a lookup VI to conver the enum to the sparse value. 

  • Enum with arbitrary values

    Is it possible to define an enum with arbitrary values as in the following C line :
    enum { MINE = 5, YOURS = 12 }
    oz

    Hi OZ,
    No, it is not possible in LabVIEW 6.0.2 or lower.
    I have read that it can be done in CVI and then exported to LabVIEW. If I had to guess I would probably say it was Jeane-Pierre Droilet (?sp), or Dr. Scott Hanna (?sp), or Rolf Kalbermatter (?sp) who posted a method for accomplishing this task.
    If you are interested in finding out how this was done I suggest you use Brian Renken's Search engine at
    http://www.searchview.net/
    to find the posting (it was posted in 2000 or 2001 I think). I believe they are called "sparse enum's".
    If you want to accomplish a similar functionality with pure "G" you could use a translator type sub-VI. The translator would use the use the enum value to index an array of constants that has the "Sparse-enum"s you want returned.
    An advantage of this method can be realized if the translator is implemented as an action engine where the "indexed-array" is read from an un-initialized shift register. This would allow redifining the enums "on-the-fly.
    I hope this helps,
    Ben
    Ben Rayner
    I am currently active on.. MainStream Preppers
    Rayner's Ridge is under construction

  • Looking for an alternative to an enum (or any non trivial type)

    Hi. I am making a class to manage geometric points, as in [x, y, z]. some languages, such as scripting language 'adobe actionscript' support certain special values such as NaN (or 'not a number'), and I can do things such as
    var _some_var:Number = Number.NaN;
    the previous sentence is something like assigning null to a pointer. NaN is not a valid value, so I can not operate with a var that has nan as a value.
    I want to do something like that in my class, but I can not use a number value and then say, 'this value is never gonna happen by itself, so if the var has that value is because is in nan state. for any value that I choose, if is a valid value, will be enough
    to consider it as an invalid alternative. instead of that, the vars are handled in pairs, so for each numeric coordinate, such as x, there is also a bool that says if the numeric value is defined
    in each point, there are the x, y and z coordinates, plus defx, defy and defz.
    the constructor is something like
    point() {
    x= 0;
    y= 0;
    z= 0;
    defx = false;
    defy=false;
    defz=false
    and since all vars are private, I use accessors such as
    setX(double _x) {
    x = _x;
    defX = true;
    so how do I assign a NaN to a var that has already a value?, or, how do I set the var 'defX' to false again?
    since setX(_some_value) is the same as x = _some_value, the idea would be that I could write something like
    setX(NaN), and that would 'undefine' X.
    since I can overload functions, and create functions with different prototypes for different types of values, even though the functions are called the same way, that's what I am doing.
    I had two choices: the first one is (copy paste from my file)
    //#ifndef _nan
    //#define _nan
    //#define NaN "NaN"
    //#endif
    not the one I chose because it does not seem better than my second choice (that's why it appears as a comment), or does not solve the problem I have with the choices I have thought so far:
    (in file 'especiales.h')
    #ifndef _especiales
    #define _especiales
    enum EEspecial {NaN};
    #endif
    and in the file for the point definition (as inline functions)
    void setX(double _x) {
                    x = _x;
                    defX = true;
            void setX(EEspecial _e) {
                    if (_e == NaN)
                        defX = false;
                    else
                        throw coordIndefException();
            double getX();
            bool definidoX() {return defX;}
    it works, it does not throw an error or there are no syntax problems; but there is a problem in my head. In the previous sentences there are two functions, one that takes a numeric value and sets it in x, and sets x as defined. on that receives not a numeric
    value but a special value, that if it turn out to be nan, will unset the x var, and set it as undefined.I checked it with these simple lines:
        geometriaPunto _ensayo;
       try {
            _ensayo.setX(NaN);
            cout << _ensayo.getX() << "\n";
        } catch (exception _e) {
            cout << _e.what() << "\n";
    this works fine. if I place a 0 in setX, it will print 0. if I place a NaN in the parenthesis, it will write the exception name. This works fine. But as far as I know, all basic var types, and all enums, also have implicit conversions to numeric values.
    so even though it works here, as I understand, telling it setX(0) is the same as setX(NaN) (which would be the implicit conversion of NaN, since is the first value in the enum). none of those are double (because I did not wrote it as setX(0.0) ), so my guess
    is that even though it works here, it was just luck, and some other c compile may understand it different, since there is not much difference between function_name(int) or function_name(enum_type)
    what would be the best way, most clear way to overload 'setX()' so it does accept a type that can not be confused with a numeric value, yet it does not make my code way more obscure and does not create ambiguity?
    tnx

    this is the last post I will make on this thread, as I find your answers useless and I already have what I need, but concerning your answers:
    "You said it worked for you in your 'adobe actionscript' code - why wouldn't the same technique work in C++ code? Number.NaN is a Number value, and it doesn't prevent you from doing operations in a var that holds that value - but that didn't
    seem to concern you before."
    have you ever worked with actionscript or did you just post because you had to post anything. yes, I can assign NaN to a numeric var in actionscript, just like I can assign null to a pointer. null is a value (0), if I add something to a var that has null,
    it will not have null anymore, if the compiler or the executable don't verify this behavior that should throw an exception. In actionscript, if a var has nan and I add something to it, it will still have nan, because nan is not a value, is a state, and probably
    actionscriopt also handles numeric vars with some other types of vars, to make these kind of validations. If I add 1 to garbage, I will still have garbage, and if I choose a random value to be chosen as nan, I or anybody else can not assure this value will
    not be the result of a valid operation
    2. "Is your question about C#, and not C++? If it is, you are in the wrong forum."
    why do you ask, did you see the previous sentences written in c#, or do you still have to answer crap if you don't answer something related to the question. if somebody has been writing things in other languages (including java or the same actionscript,
    which support that kind of behavior for properties and accessors), seems logic that I want to maintain that programing style, which will help somebody who also has been writing in those languages and then tries to read this new source, written in c++

  • Howto dynamic enum

    I'm trying to dynamically define / create a 1.5 enum. My current approach is writing my newly created enum to disk and then reading it back in with a URLClassloader.loadClass method. My first problem was a class not found exception until I pre-defined the enum. This predefined version is empty. It has no fields. I get past the not found problem, but the enum read in does not replace the empty enum. I seem to have a fundamental misunderstanding about loading class files dynamically.
    Does anyone know how to dynamically define 1.5 enums?

    I seem to have a fundamental misunderstanding about loading class files dynamically.Possibly also about what an enum is for.
    I agree with the earlier poster - you need to explain why you're doing this; it's not clear to me what you're trying to do, since the immediate interpretations wouldn't have much point to them.

  • How to create an enum?

    Hi All,
    I am trying to create my own enum to use in the report, like contract document status. But I am unable to find in setup where we define the same. Or if I can modify the existing enum ContractDocumentSystemPhaseEnum, as its not covering all the phases right now.
    Please guide where we can find enum data and define an enum.
    Thanks,
    Saloni

    Hi,
    I have created a new contract document status value list and trying to use the same in my query. As the default Value list for Contract document phase is not having all the phases defined in the workflow.
    But when I try using the new value list its not working, its working fine with the system defined value list. But as its not having all the values I need to create a new one.
    Please guide if I am missing any settings while using the new value list.
    Thanks,
    Saloni

  • Using Enums to change method behaviour

    I'm working on a neural network and I am considering using enums to define neuron types stored in a layer (e.g. input, output, hidden). My question is, could I define a single method, e.g. getNeuronError() which would behave differently dependent upon the type of neuron that is defined by the enum? Would this be a suitable method of achieving what I want or are there more suitable methods?
    Thanks for the help,
    Nick

    Nick,
    Neural nets hey... very swank.
    could I define a single method, e.g. getNeuronError() which would behave differently dependent upon the type of neuron that is defined by the enum?Well I suppose that kind of depends on what you mean by "behave differently"... How differently? Could all varieties of Neuron be shoehorned into fulfilling ONE generalised interface contract... Hmmm... maybe not huh.
    I suspect that you'd be better of defining an "enum-like" class (or class heirarchy)... which implements a ProblemSource interface which specifies a public <Problem> getProblem() method... Leaving you free to have your Neurons implementing as many specific interfaces/aspects as required... many faces, polymorphism, and all that carp.
    Just my humble opinion... Like I say... It's hard to say unless you tell us a hell of a lot more about your requirements.
    Cheers. Keith.

  • Enum type is retrieving me a null reference

    Hi, i have a very strange bug in my code that is messing me up.
    I defined two enum types in separated files like this:
    public enum Section {
         SectionA, SectionN;
    public enum Subsection {
        SubA(1, SectionA), SubN(2, SectionN);
        private Section sec;
        private int num;
        Subsection (int num, Section sec) {
            this.num = num;
            this.sec = sec;    // Here is the problem
    }Well, the problem is that in the line with the comment I'm recieving a null reference and I think that is not possible. Is that a compiler bug?

    I'm no getting any error message, let me show you my code:
    The problematic enum type.
    public enum Subseccion {
        ALUMNOS_ALTA(1, AltaAlumnos.class, "Alta", Privilegio.ALTA_ALUMNOS, Seccion.ALUMNOS),
        ALUMNOS_BUSCAR(2, BuscarAlumno.class, "Buscar", Privilegio.BUSCAR_ALUMNOS, Seccion.ALUMNOS),
        ALUMNOS_EDITAR(3, EditarAlumno.class, "Editar", Privilegio.EDITAR_ALUMNOS, Seccion.ALUMNOS),
        PERSONAL_ALTA(1, AltaPersonal.class, "Alta", Privilegio.ALTA_PROFESORES, Seccion.PERSONAL),
        PERSONAL_BUSCAR(2, BuscarPersonal.class, "Buscar", Privilegio.PERSONAL_BUSCAR, Seccion.PERSONAL),
        PERSONAL_EDITAR(3, EditarPersonal.class, "Editar", Privilegio.PERSONAL_EDITAR, Seccion.PERSONAL),
        MATERIAS(1, Materias.class, "Materias", Privilegio.ASIGNATURAS, Seccion.CURSOS),
        CURSOS(2, Cursos.class, "Cursos", Privilegio.CURSOS, Seccion.CURSOS),
        GRUPOS(3, Grupos.class, "Grupos", Privilegio.GRUPOS, Seccion.CURSOS),
        ASIGNAR_GRUPOS(4, AlumnosSalones.class, "Asignar Grupos", Privilegio.ASIGNAR_GRUPOS, Seccion.CURSOS);
        private final Class<? extends JPanel> panel;
        private final String texto;
        private final Seccion pa;  // La secci�n a la que pertenece
        private final Privilegio priv;   
        private final int importancia;
        Subseccion(int importa, Class<? extends JPanel> panel, String texto, Privilegio priv, Seccion fad) {
            this.panel = panel;
            this.texto = texto;
            if (fad == null)
                System.err.println("A NULL REFERENCE");   // Always happen
            pa = fad;
            this.priv = priv;
            this.importancia = importa;
        public int getImportancia() {
            return importancia;
         * Regresa el Panel construido que corresponde a la secci�n.
         * @param d El Objeto de base de datos que se usar� para crear el Panel.
         * @param ven El Objeto de ventana que se usar� para crear el Panel.
        public JPanel getPanelInstance(BaseDeDatosE d, VentanaPrincipal ven)
            throws InstantiationException, NoSuchMethodException, IllegalAccessException,
                    java.lang.reflect.InvocationTargetException {
            // Construyo el panel si es que hay uno asociado
            Constructor<? extends JPanel> cons = panel.getConstructor(BaseDeDatosE.class, VentanaPrincipal.class);
            JPanel panel = cons.newInstance(d, ven);
            return panel;
         * Devuelve el privilegio asociado a esta secci�n.
        public Privilegio getPrivilegio() {
            return priv;
         * Pone el "bot�n" en RollOver.
         * @param btn El "bot�n"
        public void setEstadoRollOver(JPanel btn) {
         * Pone el "bot�n" en estado presionado.
         * @param btn El "bot�n"
        public void setEstadoPresionado(JPanel btn) {
         * Devuelve la secci�n a la que pertenece.
        public Seccion getSec() {
            return pa;
         * Pone el "bot�n" en estado normal.
         * @param btn El "bot�n"
        public void setEstadoNormal(JPanel btn) {
    The enum type that is getting null.
    public enum Seccion {
        ALUMNOS(null, "/alumno", "Alumnos",
                new Subseccion[] {Subseccion.ALUMNOS_BUSCAR, Subseccion.ALUMNOS_ALTA, Subseccion.ALUMNOS_EDITAR},
                null),
        PERSONAL(null, "/profesor", "Personal",
                 new Subseccion[] {Subseccion.PERSONAL_BUSCAR, Subseccion.PERSONAL_ALTA, Subseccion.PERSONAL_EDITAR},
                 null),
        CURSOS(null, "/cursos", "Cursos",
               new Subseccion[] {Subseccion.CURSOS, Subseccion.GRUPOS, Subseccion.MATERIAS, Subseccion.ASIGNAR_GRUPOS},
               null),
        CURSOS_CALIFICAR(CalificarCursos.class, "/default", "Calificar Cursos", null, Privilegio.CALIFICAR_CURSOS),
        ASISTENCIA(Asistencia.class, "/default", "Asistencia", null, Privilegio.ASISTENCIA);
        private final Class<? extends JPanel> panel;
        private final String prefijoImagen;
        private final Subseccion[] subs;  // Las subseciones de esta secci�n
        private final String etiqueta;  // El texto que va a llevar el icono
        private final Privilegio priv;
        Seccion (Class<? extends JPanel> panel, String prefijoImagen, String etiqueta, Subseccion[] subs, Privilegio priv) {
            this.panel = panel;
            this.prefijoImagen = prefijoImagen;
            this.subs = subs;
            this.etiqueta = etiqueta;
            this.priv = priv;
         * Regresa el Panel construido que corresponde a la secci�n.
         * @param d El Objeto de base de datos que se usar� para crear el Panel.
         * @param ven El Objeto de ventana que se usar� para crear el Panel.
         * @return <code>null</code> Si no tiene un panel asociado.
        public JPanel getPanelInstance(BaseDeDatosE d, VentanaPrincipal ven)
            throws InstantiationException, NoSuchMethodException, IllegalAccessException,
                    java.lang.reflect.InvocationTargetException {
            if (panel != null) {
                // Construyo el panel si es que hay uno asociado
                Constructor<? extends JPanel> cons = panel.getConstructor(BaseDeDatosE.class, VentanaPrincipal.class);
                JPanel panel = cons.newInstance(d, ven);
                return panel;
            return null;
         * Devuelve el privilegio asociado a esta secci�n.
         * @return <code>null</code> Si no existe un privilegio asociado.
        public Privilegio getPrivilegio() {
            return priv;
         * Pone el icono de estado RollOver.
         * @param etiq El JLabel asociado a esta secci�n
        public void setIconoRollOver(JLabel etiq) {
            etiq.setIcon( new ImageIcon( getClass().getResource(prefijoImagen + "BtnOver.jpg") ) );
         * Pone el icono de estado Presionado.
         * @param etiq El JLabel asociado a esta secci�n
        public void setIconoPresionado(JLabel etiq) {
            etiq.setIcon( new ImageIcon( getClass().getResource(prefijoImagen + "Btn.jpg") ) );
         * Pone el icono de estado Normal.
         * @param etiq El JLabel asociado a esta secci�n
        public void setIconoNormal(JLabel etiq) {
            etiq.setIcon( new ImageIcon( getClass().getResource(prefijoImagen + "BtnBco.jpg") ) );           
         * Obtiene un arreglo con las subsecciones disponibles, en primer lugar la que
         * se deber�a mostrar por defecto.
         * @return <code>null</code> Si no tiene subsecciones asociadas.
        public Subseccion[] getSubsecciones() {
            return subs;
         * Le pone el texto a la etiqueta que muestra el icono de la secci�n.
        public void setTextoIcono(JLabel etiq) {
            etiq.setText(etiqueta);
    }And if you do
    Subseccion.ALUMNOS_ALTA;The message "NULL REFERENCE" is printed.

  • Help: a question about the Enum......

    Hi,
    Now I defined a Enum like below:
    public enum Seasons {  
    winter&#65292; spring&#65292; summer&#65292; fall  
    }  and here below is testing code
    System.out.println(Seasons.winter);  the console will print 0.
    Now I have a variable, its value is 2, so it should be mapping to Seasons.summer
    int idx = 2;but how to write the code to get the Seasons.summer?

    you can't (easily)
    and you shouldn't
    the whole point is that enumerations are abstract; you shouldn't be able to use them like integers and do arithmetic on them
    what are you doing that will require this?
    if you really wanted to, the Class class has a method called getEnumConstants() which returns an array of the enum objects in order of their ordinal value; so you could do something like
    Seasons.class.getEnumConstants()[2]Edited by: spoon_ on Dec 18, 2007 2:11 AM

  • Using Enum as Array Index

    Hi Experts,
    Can you please suggest whether it 's possible to use a Enum as an array index in java? In C++, I can define a enum and use the enum as the array index. But, for some reason, I 've not been able to do so in Java. Can anyone please help me in achieving this.
    Enum Index{indexOne, index2 ....};
    Index ind;
    and I should be able to use this for any array as an index:
    String s = stringArray[ind.indexOne];
    Is this possible in java? Please suggest.
    Thanks,
    Ganapathi

    Hi - the originator of this question has probably found a good answer to this question, but in case anyone else trips on this along the way:
    The oridinal() method can be used. Then spinning through the enumerated types, feels a little more like C.
    http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Enum.html
    If it helps to see an example, here's one that follows from an exercise from the Sun tutorial dealing with representing a deck of playing cards. aCard is defined as a two dimensional array (suit, rank) with the suit and rank values defined as enums and used to represent a full deck of cards. A new Card class instance is generated and assigned to the array of cards (i.e. the deck of cards made up of instances of Cards, each named aCard).
    The part to look at is simply the use of ordinal() to reference array positions.
    private Card[][] aCard = new Card[NUM_SUITS][NUM_RANKS];
    suitLoop:
    for (Suit s: Suit.values()) {
    rankLoop:
    for (Rank r: Rank.values()) {
    aCard[s.ordinal()][r.ordinal()] = new Card(s, r);
    }

Maybe you are looking for