any example of using enum to define a bunch of string consts? The string can contains special charaters like - / etc?
enum MyConstants {
STR1("some text"),
STR2("some other text");
private String value;
private MyConstants(String str) {
this.value = str;
}
public String getValue() {
return value;
}
}
then use it like this:
MyConstants.STR1.getValue();
String [] messages = {"maybe you", "better go with", "an array?"};
System.out.println (messages[1]);
Without further knowledge - why do you like to use enums at all?
I think this page will be helpful:
http://javahowto.blogspot.com/2006/10/custom-string-values-for-enum.html
In short:
public enum MyType {
ONE {
public String toString() {
return "this is one";
}
},
TWO {
public String toString() {
return "this is two";
}
}
}
Related
This is my enmun class
public enum CSSFont {
RezeptName("-fx-font: 22 calibri;"),
RezeptNameClicked("-fx-font: 22 calibri; -fx-underline: true; -fx-text-fill: purple"),
RezeptTab("-fx-font: 15 calibri;");
private String font;
private CSSFont(String s) {
this.font = s;
}
public String getFont() {
return this.font;
}
}
As you can see I created a getFont() function to get the String of each CSSFont object. Is there a way to directly make String objects in an enum class(I need the String for setStyle() methods in JavaFX), so that I don't have to always write CSSFont.object.getFont() but rather CSSFont.object? I tried to let CSSFont extend String, but obviously enums can only implement interfaces. Or is the only solution to create a class with static (final) String attributes?
EDIT: Thanks everybody, it seems I wasn't really sure when to use enums and when not to, since I have only one attribute(String) and I don't even need enumaration or comparison of these enum objects, I will use a class with static final string attributes ;).
You can use something like this:
public enum MyType {
ONE {
public String toString() {
return "this is one";
}
},
TWO {
public String toString() {
return "this is two";
}
}
}
Test it using:
public class EnumTest {
public static void main(String[] args) {
System.out.println(MyType.ONE);
System.out.println(MyType.TWO);
}
}
Originally taken from here
You can override toString method:
public enum CSSFont {
RezeptName("-fx-font: 22 calibri;"),
RezeptNameClicked("-fx-font: 22 calibri; -fx-underline: true; -fx-text-fill: purple"),
RezeptTab("-fx-font: 15 calibri;");
private String font;
private CSSFont(String s) {
this.font = s;
}
public String getFont() {
return this.font;
}
public String toString(){
return this.font;
}
}
Then you can get font as follows:
CSSFont.RezeptName.toString()
I am new student java learning its basics
My objective is to create a Enum which contains various categories like Emails, Username, Passwords, MaterialType etc.
Further I wanted that within one Category I can declare various strings and my sample code is as below:
public enum MyEnums {
Usernames
{
public String toString()
{
return "This is a GmailUsername";
}
/*public String toString()
{
return "This is a GalleryComment";
}*/
},
Password
{
public String toString()
{
return "This is a public password";
}
/* public String GmailPassword()
{
return "This is a Gmail Password";
} */
},
Emails
{
public String toString()
{
return "This is a public contact email address";
}
/* public String EmailAccount()
{
return "This is a public Email Account address";
} */
},
PhoneNumbers
{
public String toString()
{
return "This is Phonenumber";
}
/* public String Phone()
{
return "This is a phone number";
}*/
}
}
and I call the code as
public static void main (String args[])
{
System.out.println(MyEnums.Emails);
System.out.println(MyEnums.Usernames );
System.out.println(MyEnums.PhoneNumbers);
System.out.println(MyEnums.Password);
}
My question is why on using second string type function it is giving error, example In the password category for GmailPassword() why it is not working.
Is there is any other way to declare multiple strings in enum in category wise manner like
public Enum myEnum{
Category1
{
"String 1","String2",......."String N"
}
.......
.......
.......
.......
CategoryN
{
"String 1","String2",......."String N"
}
maybe this helps?
public enum MyEnum {
Emails("mail1", "mail2", "mail3"),
Usernames("username1", "username2"),
CategoryN("a", "b", "c");
private String[] strings;
private MyEnum(String... strings) {
this.strings = strings;
}
#Override
public String toString() {
return Arrays.toString(strings);
}
public String getString(int index) {
return strings[index];
}
}
Main
public static void main(String[] args) {
System.out.println(MyEnum.Emails); //[mail1, mail2, mail3]
System.out.println(MyEnum.Emails.getString(1)); //mail2
}
You can create an enum with Objects instead of just Strings. That way you can access all the properties of those objects in a clean manner.
It seems to me that instead of an Enum with categories, you should have an interface that you make each category enum implement. That way you have N enums that each implement the category interface, and inside each of those you have the strings as the enum constants.
enum generalInformation {
NAME {
#Override
public String toString() {
return "Name";
}
},
EDUCATION {
#Override
public String toString() {
return "Education";
}
},
EMAIL {
#Override
public String toString() {
return "Email";
}
},
PROFESSION {
#Override
public String toString() {
return "Profession";
}
},
PHONE {
#Override
public String toString() {
return "Phone";
}
}
}
I have that information are avaiable in enum.
How to print all enum values like: print.generalInformation?
That outputs:
Name
Education
Email
Phone
How to pass that enum generalInformation as an arg in another function?
System.out.println(java.util.Arrays.asList(generalInformation.values()));
Your second part... Just the same as an interface or a class
Firstly, I would refactor your enum to pass the string representation in a constructor parameter. That code is at the bottom.
Now, to print all enum values you'd just use something like:
// Note: enum name changed to comply with Java naming conventions
for (GeneralInformation info : EnumSet.allOf(GeneralInformation.class)) {
System.out.println(info);
}
An alternative to using EnumSet would be to use GeneralInformation.values(), but that means you have to create a new array each time you call it, which feels wasteful to me. Admittedly calling EnumSet.allOf requires a new object each time too... if you're doing this a lot and are concerned about the performance, you could always cache it somewhere.
You can use GeneralInformation just like any other type when it comes to parameters:
public void doSomething(GeneralInformation info) {
// Whatever
}
Called with a value, e.g.
doSomething(GeneralInformation.PHONE);
Refactoring using a constructor parameter
public enum GeneralInformation {
NAME("Name"),
EDUCATION("Education"),
EMAIL("Email"),
PROFESSION("Profession"),
PHONE("Phone");
private final String textRepresentation;
private GeneralInformation(String textRepresentation) {
this.textRepresentation = textRepresentation;
}
#Override public String toString() {
return textRepresentation;
}
}
With your current values, you could actually just convert the name to title case automatically - but that wouldn't be very flexible for the long term, and I think this explicit version is simpler.
Since Java 8 I would suggest the following solution:
public static String printAll() {
return Stream.of(GeneralInformation.values()).
map(GeneralInformation::name).
collect(Collectors.joining(", "));
}
In applications, it's good practice to separate data from presentation. It allows the data to be used in different user interfaces, it makes the data objects more lightweight, and it allows for the future possibility of internationalization.
With that in mind, it's good to avoid strongly coupling the display name to the enum constant. Fortunately, there is a class which makes this easy: EnumMap.
public class ApplicationUI {
private final Map<GeneralInformation, String> names;
public ApplicationUI() {
names = new EnumMap<>(GeneralInformation.class);
names.put(GeneralInformation.NAME, "Name");
names.put(GeneralInformation.EDUCATION, "Education");
names.put(GeneralInformation.EMAIL, "Email");
names.put(GeneralInformation.PROFESSION, "Profession");
names.put(GeneralInformation.PHONE, "Phone");
assert names.keySet().containsAll(
EnumSet.allOf(GeneralInformation.class)) :
"Forgot to add one or more GeneralInformation names";
}
public String getNameFor(GeneralInformation info) {
return names.get(info);
}
}
If you are still on Java 1.7 this is what worked for me:
String genInfoValues = "";
boolean firstRun = true;
for (generalInformation info : generalInformation.values()){
if (firstRun) {
firstRun = false;
genInfoValues += info.name();
} else {
genInfoValues += ", " + info.name();
}
}
values() on the enum returns an array. So, it would be simple to do the following to:
System.out.println(Arrays.toString(generalInformation.values()));
What's the best way to store this data in a Java enum?
<select>
<option></option>
<option>Recommend eDelivery</option>
<option>Require eDelivery</option>
<option>Require eDelivery unless justification provided</option>
</select>
I'm new to java and have tried things like
public enum Paperless {
"None" = null,
"Recommend eDelivery" = "Recommend eDelivery",
"Require eDelivery" = "Require eDelivery",
"Require eDelivery unless justification provided" = "Require eDelivery w/out justification"
}
But this doesn't work. I'm considering the possibility of storing a text value that summarizes the option that the user sees on this web page.
Take a look at the enum tutorial, more specifically the Planet example. You can do the same, e.g.
public enum Paperless{
NONE( null ),
RECOMMENDED_DELIVERY( "Recommended delivery" ),
...//put here the other values
REQUIRED_DELIVERY( "Required delivery" );
private String name;
Paperless( String name ){
this.name = name;
}
public String getName(){
return this.name;
}
}
Something like this can work for your case:
public enum PaperLess {
NONE("none"),
RECOMMEND("Recommend eDelivery"),
REQUIRE("Require eDelivery"),
REQUIRE_JUSTIFIED("Require eDelivery unless justification provided");
private String value;
private PaperLess(String value) {
this.value = value;
}
public String getValue() {
return value;
}
}
You can't assign strings to enum values in Java in the way that you are trying.
The way to do it would be:
public enum Paperless {
None(null),
RecommendedDelivery("Recommended Delivery"),
RequireEDelivery("Require eDelivery"),
RequireEDeliveryUnlessJustification("Require eDelivery unless justification provided");
private final String value;
Paperless(String value) {
this.value = value;
}
private String enumValue() { return value; }
public static void main(String[] args) {
for (Paperless p : Paperless.values())
System.out.println("Enum:" + p + "; Value:" + p.enumValue());
}
}
You can't have spaces in the names of members and you can't assign enum values, they are objects, not constants.
The name of the enum must be an identifier (e.g. one-word, not a string)
public enum Paperless {
None,
RecommendEDelivery,
...
}
You can associate string values with them if you want (although you can get the default too that equals to the identifier name, usign the name() method) by associating a String member with the enum type and providing a custom constructor.
public enum Paperless {
None("None"),
RecommendEDelivery("Recommend eDelivery"),
...;
private String myValue;
private Paperless(String name) {myValue=name;)
}
To access that associated string, you need to provide a public accessor method as well.
Java enums aren't constructed in that way. Check out
Java Tutorials: Enum Types
Java - Convert String to enum: #2
Yours might look something like this:
public enum Paperless {
NONE(""),
RECOMMEND("Recommend eDelivery"),
REQUIRE("Require eDelivery"),
REQUIRE_UNLESS("Require eDelivery unless justification provided");
private String text;
Paperless(String text) {
this.text = text;
}
public String getText() {
return this.text;
}
}
public enum Paperless {
NONE("None"),
RECOMMEND("Recommend eDelivery"),
REQUIRE("Require eDelivery"),
REQUIRE_UNLESS("Require eDelivery unless justification provided"),;
private String value;
private Paperless(String value){
this.value=value;
}
public String getValue(){
return this.value;
}
}
Given this enum:
public enum FileTypes {
FILEA, FILEB, FILEC;
}
Say you want to see if a String value matches one of the 3 enum types, I have this method:
public static boolean validFileType(String value) {
for (FileTypes fileTypes : FileTypes.values()) {
if (fileTypes.name().equals(value)) {
return true;
}
}
return false;
}
That works fine, now I'd like to change things a bit. Can I add multiple Strings to match for a single enum? Let's say the String value is "FILEA" or "example-file", could I have both of those specified in the enum? I'd like to keep those in the enum rather than have if statements outside the enum performing the mapping.
Hope that makes sense, thanks for any ideas
You should add field(s) to your enum and then implement kind of your own valueOf() method. Please take a look on article that gives more details: http://java.dzone.com/articles/enum-tricks-customized-valueof
You could add the valid entries to you enum constructor like this:
public enum FileTypes {
FILEA("example_file"), //2 valid types
FILEB("example2", "example3"), //3 valid types
FILEC(); //Only "FILEC" is valid
FileTypes(String... otherValidEntries) {
this.validEntries.add(this.toString()); //I assume that the name of the enum is valid
this.validEntries.addAll(Arrays.asList(otherValidEntries));
}
private List<String> validEntries = new ArrayList<String>();
public static boolean isValidFileType(String value) {
for (FileTypes fileTypes : FileTypes.values()) {
if (fileTypes.validEntries.contains(value)) {
return true;
}
}
return false;
}
}
Example use:
public static void main(String[] args) {
System.out.println(FileTypes.isValidFileType("FILEA")); //true
System.out.println(FileTypes.isValidFileType("FILEB")); //true
System.out.println(FileTypes.isValidFileType("example2")); //true
System.out.println(FileTypes.isValidFileType("example3")); //true
System.out.println(FileTypes.isValidFileType("FILEC")); //true
System.out.println(FileTypes.isValidFileType("example4")); //false
}
You can add a field to the enum:
public enum FileTypes
{
FILEA("FILEA"), FILEB("FILEB", "file_b"), FILEC("FILEC", "file_c", "File of type C", "C_FILE");
private String[] aliases;
private FileTypes(String... aliases){
this.aliases = aliases;
}
public boolean equals(String string){
for(int i = 0; i < aliases.length; i++){
if(aliases[i].equals(string)){
return true;
}
}
return false;
}
}
and then:
public static boolean validFileType(String value) {
for (FileTypes fileType : FileTypes.values()) {
if (fileTypes.equals(value)) {
return true;
}
}
return false;
}
public enum FileTypes {
FILEA(Arrays.asList("fileA", "the first one")),
FILEB(Arrays.asList("fileB")),
FILEC(Arrays.asList("fileC"));
private final Collection<String> val;
private FileTypes(Collection<String> val) {
this.val = val;
}
public static FileTypes findByValue(String val) {
for (FileTypes ft : values()) {
if (ft.val.contains(val)) {
return ft;
}
}
throw new IllegalArgumentException("There's no such file type identified by " + val);
}
}
FILEA can be found either by fileA or the first one:
System.out.println("file a: " + FileTypes.findByValue("fileA"));
System.out.println("file a: " + FileTypes.findByValue("the first one"));
Yes
Map<String, FileTypes> map = new HashMap<>();
map.put("FILEA", FileTypes.FILEA);
map.put("example-file", FileTypes.FILEA);
boolean validFileType(String value) {
return map.containsKey(value);
}
You get the idea... If you want to closely couple valid "values" with their enums, you could create the enum like this:
public enum FileTypes {
FILEA("FILEA", "example-file"),
FILEB("FILEB"),
FILEC("FILEC");
private final List<String> values;
private FileTypes(String... values) {
this.values = Arrays.asList(values);
}
public boolean validFileType(String value) {
return values.contains(value);
}
}