473,788 Members | 3,068 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

getting Enum constant

98 New Member
I have the following enum.

Expand|Select|Wrap|Line Numbers
  1. **
  2.  * An enum to represent types of mechanics.
  3.  * 
  4.  * @author 
  5.  * @version 1.0
  6.  */
  7. public enum Mechanics {
  8.     ISOLATION(0),
  9.     COMPOUND(1);
  10.  
  11.     /**
  12.      * Variable to hold the value of the mechanics.
  13.      */
  14.     private final int mechanics;
  15.  
  16.     /**
  17.      * Constructor to create a mechanics
  18.      * 
  19.      * @variable    newMechanics
  20.      *                 The value of the new mechanics
  21.      */
  22.     Mechanics (int newMechanics) {
  23.         this.mechanics = newMechanics;
  24.     }
  25.  
  26.     /**
  27.      * An inspector method that returns the value of the calling operation.
  28.      * 
  29.      * @return     the value of the calling mechanics.
  30.      *             | result >= 0 && result < 2
  31.      */
  32.      public int getValue(){
  33.          return mechanics;
  34.      }
  35.  
  36.      /**
  37.       * A method to check whether the value of a given mechanics
  38.       * matches that of this mechanics
  39.       * 
  40.       * @variable    other
  41.       *             The mechanics to be compared with this mechanics
  42.       */
  43.      public boolean equals(Mechanics other){
  44.          return this.getValue() == other.getValue();
  45.      }
  46. }
Now, I also have objects, which have a property that is a constant of this Enum. (isolation or compound). Now I am searching for a way of saving these objects (to textfiles), and loading them.

Which means that the property of the object which is the enum should be saved in a way (i guess using the associated int) that is simple.

Also I should be able to load this enum again. However I do not know how to do this, since a constructor of an enum is private, and the method that loads does not know wether the 0 or 1 stands for isolation or compound.

How can I do this, without using switch-like things? I have much larger enums then the one I showed here.

Thanks
Aug 11 '08 #1
3 2264
BigDaddyLH
1,216 Recognized Expert Top Contributor
Your enum is over-engineered ;-)

The following in sufficient:

Expand|Select|Wrap|Line Numbers
  1. public enum Mechanics {ISOLATION, COMPOUND};
There is no need to define a "value" property as you did. Enum defines a property ordinal that does the same thing. Enum also overrides toString, equals, hashCode and clone correctly. Enums implements Serializable and Comparable as well.

To save and restore an enum, you can convert it to a String and back:

Expand|Select|Wrap|Line Numbers
  1. String s = m1.name(); //or m1.toString();
  2. Mechanics m2 = Mechanics.valueOf(s);
or convert it to its ordinal and back:

Expand|Select|Wrap|Line Numbers
  1. int ord = m1.ordinal();
  2. Mechanics m2 = Mechanics.values()[ord];
As mentioned, enums are serializable so you could save and restore objects with enum fields that way, but java beans can be persisted with XMLEncoder/Decoder as well:

Expand|Select|Wrap|Line Numbers
  1. public class SaveMe {
  2.     private Mechanics mech;
  3.     private int another;
  4.  
  5.     public SaveMe() {
  6.     }
  7.  
  8.     public SaveMe(Mechanics mech, int another) {
  9.         setMechanics(mech);
  10.         setAnother(another);
  11.     }
  12.  
  13.     public void setMechanics(Mechanics mech) {
  14.         this.mech = mech;
  15.     }
  16.  
  17.     public Mechanics getMechanics() {
  18.         return mech;
  19.     }
  20.  
  21.     public void setAnother(int another) {
  22.         this.another = another;
  23.     }
  24.  
  25.     public int getAnother() {
  26.         return another;
  27.     }
  28.  
  29.     public String toString() {
  30.         return String.format("[mech=%s, another=%d]",
  31.             getMechanics(), getAnother());
  32.     }
  33. }
Expand|Select|Wrap|Line Numbers
  1. import java.beans.*;
  2. import java.io.*;
  3.  
  4. public class EnumTest {
  5.     public static void main(String[] args)  throws IOException {
  6.         testParse();
  7.         testIO();
  8.     }
  9.  
  10.     static void testParse() {
  11.         String[] input = {"ISOLATION","COMPOUND"};
  12.         for(String s : input) {
  13.             Mechanics m = Mechanics.valueOf(s);
  14.             System.out.format("%s --> %s, with ordinal %d%n", s, m, m.ordinal());
  15.         }
  16.     }
  17.  
  18.     static void testIO() throws IOException {
  19.         File file = new File("test.xml");
  20.  
  21.         XMLEncoder e = new XMLEncoder(
  22.             new BufferedOutputStream(
  23.                 new FileOutputStream(file)));
  24.         e.writeObject(new SaveMe(Mechanics.COMPOUND, 17));
  25.         e.close();
  26.  
  27.         XMLDecoder d = new XMLDecoder(
  28.             new BufferedInputStream(
  29.             new FileInputStream(file)));
  30.         Object result = d.readObject();
  31.         d.close();
  32.         System.out.println(result);
  33.     }
  34. }
The method testIO create the file test.xml:

Expand|Select|Wrap|Line Numbers
  1. <?xml version="1.0" encoding="UTF-8"?> 
  2. <java version="1.6.0" class="java.beans.XMLDecoder"> 
  3.  <object class="SaveMe"> 
  4.   <void property="another"> 
  5.    <int>17</int> 
  6.   </void> 
  7.   <void property="mechanics"> 
  8.    <object class="Mechanics" method="valueOf"> 
  9.     <string>COMPOUND</string> 
  10.    </object> 
  11.   </void> 
  12.  </object> 
  13. </java> 
  14.  
Conclusion: enums are simpler and easier to use than you first thought!
Aug 12 '08 #2
Gangreen
98 New Member
I see. Damn I thought they weren't that easy.

Thanx for everything!
Aug 13 '08 #3
BigDaddyLH
1,216 Recognized Expert Top Contributor
ps.

There are times when it makes sense to add methods (even polymorphic methods) to an enumerated type, Check out the Planet and Operation examples:

[http://java.sun.com/j2se/1.5.0/docs/guide/language/enums.html]
Aug 14 '08 #4

Sign in to post your reply or Sign up for a free account.

Similar topics

20
4851
by: Glenn Venzke | last post by:
I'm writing a class with a method that will accept 1 of 3 items listed in an enum. Is it possible to pass the item name without the enum name in your calling statement? EXAMPLE: public enum EnumName FirstValue = 1 SecondValue = 2 ThirdValue = 3
3
12371
by: Ajax Chelsea | last post by:
can not the "static const int" be replaced by "static enum" anywhere? is it necessary that define special initialization syntax for "static const int"?
21
6367
by: Bilgehan.Balban | last post by:
Hi, I have two different enum definitions with members of same name. The compiler complains about duplicate definitions. Is this expected behaviour? Can't I have same-named fields in different enum definitions? I think it should have been perfectly valid to do that. Its a stupid limitation to have to define disjoint enum symbol definitions. This is like having to have disjoint member names in structures.
10
10516
by: Russell Shaw | last post by:
Hi, gcc-3.4 complains about non-integers in: enum {IDENTIFIER = "<identifier>", WIDGETDEF = "widgetdef"}; even if i cast the strings to integers.
5
4530
by: Sriram Rajagopalan | last post by:
Hi, Is the extra comma at the end of an enumerator-list valid according to the C standards? With the gcc compiler the following is valid: enum DAYS {MONDAY, TUESDAY, }day1; gcc does not even *warn* about the extra comma after "TUESDAY".
12
3361
by: Laurent Deniau | last post by:
If I understand well, an enumeration is only garantee to hold at most an int (6.7.2.2-2). So I would like to know: how to store a long in an enum? enum { p2_31 = 1L << 31 }; // boom how to define a synonym of a constant address?
10
23615
by: kar1107 | last post by:
Hi all, Can the compiler chose the type of an enum to be signed or unsigned int? I thought it must be int; looks like it changes based on the assigned values. Below if I don't initialize FOO_STORE to be, say -10, I get a warning about unsigned comparison and I'm seeing an infinite loop. If I do initialize FOO_STORE = -10, I don't see any warnings. No infinite loop.
34
11205
by: Steven Nagy | last post by:
So I was needing some extra power from my enums and implemented the typesafe enum pattern. And it got me to thinking... why should I EVER use standard enums? There's now a nice little code snippet that I wrote today that gives me an instant implementation of the pattern. I could easily just always use such an implementation instead of a standard enum, so I wanted to know what you experts all thought. Is there a case for standard enums?
21
7020
by: srikar | last post by:
hi all when I am running the below program #include<iostream> enum one { a=1000,b=2000,c,d,z}; int main() { one* a1;one* a2;one* a3;
0
9498
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10172
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10110
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9964
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8993
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5398
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5535
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4069
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2894
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.