I have the following enum. - **
-
* An enum to represent types of mechanics.
-
*
-
* @author
-
* @version 1.0
-
*/
-
public enum Mechanics {
-
ISOLATION(0),
-
COMPOUND(1);
-
-
/**
-
* Variable to hold the value of the mechanics.
-
*/
-
private final int mechanics;
-
-
/**
-
* Constructor to create a mechanics
-
*
-
* @variable newMechanics
-
* The value of the new mechanics
-
*/
-
Mechanics (int newMechanics) {
-
this.mechanics = newMechanics;
-
}
-
-
/**
-
* An inspector method that returns the value of the calling operation.
-
*
-
* @return the value of the calling mechanics.
-
* | result >= 0 && result < 2
-
*/
-
public int getValue(){
-
return mechanics;
-
}
-
-
/**
-
* A method to check whether the value of a given mechanics
-
* matches that of this mechanics
-
*
-
* @variable other
-
* The mechanics to be compared with this mechanics
-
*/
-
public boolean equals(Mechanics other){
-
return this.getValue() == other.getValue();
-
}
-
}
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
3 2264 BigDaddyLH 1,216
Recognized Expert Top Contributor
Your enum is over-engineered ;-)
The following in sufficient: - 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: - String s = m1.name(); //or m1.toString();
-
Mechanics m2 = Mechanics.valueOf(s);
or convert it to its ordinal and back: - int ord = m1.ordinal();
-
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: - public class SaveMe {
-
private Mechanics mech;
-
private int another;
-
-
public SaveMe() {
-
}
-
-
public SaveMe(Mechanics mech, int another) {
-
setMechanics(mech);
-
setAnother(another);
-
}
-
-
public void setMechanics(Mechanics mech) {
-
this.mech = mech;
-
}
-
-
public Mechanics getMechanics() {
-
return mech;
-
}
-
-
public void setAnother(int another) {
-
this.another = another;
-
}
-
-
public int getAnother() {
-
return another;
-
}
-
-
public String toString() {
-
return String.format("[mech=%s, another=%d]",
-
getMechanics(), getAnother());
-
}
-
}
- import java.beans.*;
-
import java.io.*;
-
-
public class EnumTest {
-
public static void main(String[] args) throws IOException {
-
testParse();
-
testIO();
-
}
-
-
static void testParse() {
-
String[] input = {"ISOLATION","COMPOUND"};
-
for(String s : input) {
-
Mechanics m = Mechanics.valueOf(s);
-
System.out.format("%s --> %s, with ordinal %d%n", s, m, m.ordinal());
-
}
-
}
-
-
static void testIO() throws IOException {
-
File file = new File("test.xml");
-
-
XMLEncoder e = new XMLEncoder(
-
new BufferedOutputStream(
-
new FileOutputStream(file)));
-
e.writeObject(new SaveMe(Mechanics.COMPOUND, 17));
-
e.close();
-
-
XMLDecoder d = new XMLDecoder(
-
new BufferedInputStream(
-
new FileInputStream(file)));
-
Object result = d.readObject();
-
d.close();
-
System.out.println(result);
-
}
-
}
The method testIO create the file test.xml: - <?xml version="1.0" encoding="UTF-8"?>
-
<java version="1.6.0" class="java.beans.XMLDecoder">
-
<object class="SaveMe">
-
<void property="another">
-
<int>17</int>
-
</void>
-
<void property="mechanics">
-
<object class="Mechanics" method="valueOf">
-
<string>COMPOUND</string>
-
</object>
-
</void>
-
</object>
-
</java>
-
Conclusion: enums are simpler and easier to use than you first thought!
I see. Damn I thought they weren't that easy.
Thanx for everything!
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]
Sign in to post your reply or Sign up for a free account.
Similar topics |
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
|
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"?
|
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.
|
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.
|
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".
| |
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?
|
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.
|
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?
|
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;
|
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,...
|
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...
| |
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,...
|
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...
|
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...
|
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...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
|
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
| |
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...
| |