Enum within enum - java

I want to create an enum within an enum for sql query in java. For example I want to say table.create and it would return CREATE TABLE or database.create and it would return CREATE DATABASE. How can I do this?
enum SQL {
table("ALTER,CREATE"),
database("CREATE");
}

Define an enum within the enum:
public static enum SQL {
table(Command.ALTER,Command.CREATE),
database(Command.CREATE);
public static enum Command {
CREATE,
ALTER
}
private final Command[] commands;
private SQL (Command... commands) {
this.commands = commands;
}
public Command[] getCommands() {
return commands;
}
}
Although you can do this, it would be better to declare the Command enum in its own class/file. I haven't seen anyone declare an enum inside another enum before... I almost like it.

Why make it an enum within an enum?
Table.java
public enum Table {
CREATE("CREATE TABLE"),
ALTER("ALTER TABLE");
private String cmd;
Table(String cmd) {
this.cmd = cmd;
}
#Override
public String toString() {
return cmd;
}
}
Database.java
public enum Database {
CREATE("CREATE DATABASE");
private String cmd;
Database(String cmd) {
this.cmd = cmd;
}
#Override
public String toString() {
return cmd;
}
}
With this example, System.out.println(Table.CREATE); prints CREATE TABLE.
This will also aid in readabilty becuase you can produce code like:
String query = Table.CREATE + "(Column1 " + DbType.INTEGER + " " + Column.UNIQUE + " " + Column.PRIMARY_KEY + ")";
Which would be a bit easier to read and understand, IMO.
EDIT
To attempt to get close to what you're after you could do something like:
public enum SQL {
TABLE("TABLE", SQL.CREATE_FLAG | SQL.ALTER_FLAG),
DATABASE("DATABASE", SQL.CREATE_FLAG);
public static final int CREATE_FLAG = 1;
public static final int ALTER_FLAG = 2;
public static final String CREATE_STRING = "CREATE";
public static final String ALTER_STRING = "ALTER";
public static final String INVALID = "INVALID";
private String name;
private boolean create;
private boolean alter;
SQL(String name, int flags) {
create = (flags & CREATE_FLAG) != 0;
alter = (flags & ALTER_FLAG) != 0;
this.name = name;
}
public String create() {
if (create)
return CREATE_STRING + " " + name;
else
return INVALID;
}
public String alter() {
if (alter)
return ALTER_STRING + " " + name;
else
return INVALID;
}
}
Where you can call:
System.out.println(SQL.TABLE.create()); // CREATE TABLE
System.out.println(SQL.TABLE.alter()); // ALTER TABLE
System.out.println(SQL.DATABASE.alter()); // INVALID
System.out.println(SQL.DATABASE.create()); // CREATE DATABASE

Related

How can I use the indexOf() function to find an object with a certain property

I have an object, Pet, and one of the functions is to retrieve its name.
public class pet{
private String petName;
private int petAge;
public pet(String name, int age){
petName = name;
petAge = age;
}
public String getName(){
return petName;
}
public int getAge(){
return petAge;
}
}
I then have an ArrayList which holds a collection of pets as shown in the code below:
import java.util.ArrayList;
pet Dog = new pet("Orio", 2);
pet Cat = new pet("Kathy", 4);
pet Lion = new pet("Usumba", 6);
ArrayList<pet> pets = new ArrayList<>();
pets.add(Dog);
pets.add(Cat);
pets.add(Lion;
I was wondering how I could retrieve the index in the ArrayList or the object that has the name I need. So if I wanted to find out how old Usumba was, how would I do this?
Note: This is not my actual piece of code, it's just used so that I can better explain my problem.
Edit 1
So far, I have the following but I was wondering if there was a better or more efficient way
public int getPetAge(String petName){
int petAge= 0;
for (pet currentPet : pets) {
if (currentPet.getName() == petName){
petAge = currentPet.getAge();
break;
}
}
return petAge;
}
You can't use indexOf() for this purpose, unless you abuse the purpose of the equals() method.
Use a for loop over an int variable that iterates from 0 to the length of the List.
Inside the loop, compare the name if the ith element, and if it's equal to you search term, you've found it.
Something like this:
int index = -1;
for (int i = 0; i < pets.length; i++) {
if (pets.get(i).getName().equals(searchName)) {
index = i;
break;
}
}
// index now holds the found index, or -1 if not found
If you just want to find the object, you don't need the index:
pet found = null;
for (pet p : pets) {
if (p.getName().equals(searchName)) {
found = p;
break;
}
}
// found is now something or null if not found
As the others already stated, you cannot use indexOf() for this directly. It would be possible in certain situations (lambdas, rewriting hashCode/equals etc), but that is usually a bad idea because it would abuse another concept.
Here's a few examples of how we can do that in modern Java:
(as the index topic has already been answered quite well, this only handles direct Object return)
package stackoverflow.filterstuff;
import java.util.ArrayList;
import java.util.Objects;
import java.util.function.Function;
import java.util.function.Predicate;
public class FilterStuff {
public static void main(final String[] args) {
final Pet dog = new Pet("Orio", 2); // again, naming conventions: variable names start with lowercase letters
final Pet cat = new Pet("Kathy", 4);
final Pet lion = new Pet("Usumba", 6);
final ArrayList<Pet> pets = new ArrayList<>();
pets.add(dog);
pets.add(cat);
pets.add(lion);
try {
simpleOldLoop(pets);
} catch (final Exception e) {
e.printStackTrace(System.out);
}
try {
simpleLoopWithLambda(pets);
} catch (final Exception e) {
e.printStackTrace(System.out);
}
try {
filterStreams(pets);
} catch (final Exception e) {
e.printStackTrace(System.out);
}
try {
filterStreamsWithLambda(pets);
} catch (final Exception e) {
e.printStackTrace(System.out);
}
}
private static void simpleOldLoop(final ArrayList<Pet> pPets) {
System.out.println("\nFilterStuff.simpleOldLoop()");
System.out.println("Pet named 'Kathy': " + filterPet_simpleOldLoop(pPets, "Kathy"));
System.out.println("Pet named 'Hans': " + filterPet_simpleOldLoop(pPets, "Hans"));
}
private static Pet filterPet_simpleOldLoop(final ArrayList<Pet> pPets, final String pName) {
if (pPets == null) return null;
for (final Pet pet : pPets) {
if (pet == null) continue;
if (Objects.equals(pet.getName(), pName)) return pet;
}
return null;
}
private static void simpleLoopWithLambda(final ArrayList<Pet> pPets) {
System.out.println("\nFilterStuff.simpleLoopWithLambda()");
System.out.println("Pet named 'Kathy': " + filterPet_simpleLoopWithLambda(pPets, (pet) -> Boolean.valueOf(Objects.equals(pet.getName(), "Kathy"))));
System.out.println("Pet named 'Hans': " + filterPet_simpleLoopWithLambda(pPets, (pet) -> Boolean.valueOf(Objects.equals(pet.getName(), "Hans"))));
}
private static Pet filterPet_simpleLoopWithLambda(final ArrayList<Pet> pPets, final Function<Pet, Boolean> pLambda) {
if (pPets == null) return null;
for (final Pet pet : pPets) {
if (pet == null) continue;
final Boolean result = pLambda.apply(pet);
if (result == Boolean.TRUE) return pet;
}
return null;
}
private static void filterStreams(final ArrayList<Pet> pPets) {
System.out.println("\nFilterStuff.filterStreams()");
System.out.println("Pet named 'Kathy': " + filterPet_filterStreams(pPets, "Kathy"));
System.out.println("Pet named 'Hans': " + filterPet_filterStreams(pPets, "Hans"));
}
private static Pet filterPet_filterStreams(final ArrayList<Pet> pPets, final String pName) {
return pPets.stream().filter(p -> Objects.equals(p.getName(), pName)).findAny().get();
}
private static void filterStreamsWithLambda(final ArrayList<Pet> pPets) {
System.out.println("\nFilterStuff.filterStreamsWithLambda()");
System.out.println("Pet named 'Kathy': " + filterPet_filterStreams(pPets, p -> Objects.equals(p.getName(), "Kathy")));
final Predicate<Pet> pdctHans = p -> Objects.equals(p.getName(), "Hans"); // we can also have 'lambda expressions' stored in variables
System.out.println("Pet named 'Hans': " + filterPet_filterStreams(pPets, pdctHans));
}
private static Pet filterPet_filterStreams(final ArrayList<Pet> pPets, final Predicate<Pet> pLambdaPredicate) {
return pPets.stream().filter(pLambdaPredicate).findAny().get();
}
}
Along with your Pet class, extended by toString():
package stackoverflow.filterstuff;
public class Pet { // please stick to naming conventions: classes start with uppercase letters!
private final String petName;
private final int petAge;
public Pet(final String name, final int age) {
petName = name;
petAge = age;
}
public String getName() {
return petName;
}
public int getAge() {
return petAge;
}
#Override public String toString() {
return "Pet [Name=" + petName + ", Age=" + petAge + "]";
}
}

Finding and changing tuples values

I have some tuples already made like so:
public GreenhouseControls() {
light = new Tuple<>("light", "off");
fans = new Tuple<>("fans", "off");
water = new Tuple<>("water", "off");
power = new Tuple<>("power", "on");
window = new Tuple<>("window", "good");
thermostat = new Tuple<>("thermostat","day");
}
and I'm trying to use a setVariable() method in the same class that will take in 2 string (for example, "light" and "on") and would use the first string to search the first variable of the tuple and when a match is found it would replace the second variable with the second string.
I tried adding the tuples to an ArrayList but I can't get the search part to work.
Is there a way to achieve this maybe with either an ArrayList or a HashSet?
Tuple class:
public static class Tuple<A,B> {
public final A eventName;
public final B status;
public Tuple(A eventName, B status) {
this.eventName = eventName;
this.status = status;
}
public String toString() {
return "(" + eventName + ", " + status + ")";
}
}
You can use a Map to create relationships between keys and values. In your case, a HashMap would be appropriate and would make your code much more concise and easy to read. You can use put(key,value) to set the value of a key and use get(key) to retrieve the value associated with a key.
final Map<String, String> map = new HashMap<>();
map.put("light","off");
//Etc..
//Get value
String light = map.get("light");//"off"
//Update value
map.put("light","on");
light = map.get("light");//"on"
If you are not allowed to change the structure of your code, you can implement it with your Tuple class using foreach loops like so:
import java.util.Arrays;
import java.util.List;
public class GreenhouseControls {
private final List<Tuple<String,String>> members;
public GreenhouseControls() {
members = Arrays.asList(
new Tuple<>("light", "off"),
new Tuple<>("fans", "off"),
new Tuple<>("water", "off"),
new Tuple<>("power", "on"),
new Tuple<>("window", "good"),
new Tuple<>("thermostat","day")
);
}
public void setVariable(final String eventName, final String status) {
for(final Tuple<String, String> tuple: members) {
if(tuple.getEventName().equals(eventName)) {
tuple.setStatus(status);
return;
}
}
throw new IllegalArgumentException("No event found with eventName " + eventName);
}
public String getVariable(final String eventName) {
for(final Tuple<String, String> tuple: members) {
if(tuple.getEventName().equals(eventName)) {
return tuple.getStatus();
}
}
return null;
}
public static class Tuple<A, B> {
private A eventName;
private B status;
public Tuple(final A eventName, final B status) {
this.eventName = eventName;
this.status = status;
}
#Override
public String toString() {
return "(" + eventName + ", " + status + ")";
}
public B getStatus() {
return status;
}
public void setStatus(B status) {
this.status = status;
}
public A getEventName() {
return eventName;
}
}
}
I've implemented how you could do this for a single variable of an object. i.e. "Light".
Is there a reason why you need to have a redundant variable captured as a tuple?
public class GreenhouseControls {
private String light;
public String getLightStatus() {
return light;
}
public void setLightStatus(String input)
{
if(input == "on" || input == "off")
this.light = input;
}
public static void main(String[] args)
{
GreenhouseControls controls = new GreenhouseControls();
controls.setLightStatus("on");
System.out.println(controls.getLightStatus());
controls.setLightStatus("off");
System.out.println(controls.getLightStatus());
}
}
The easier way is to use HashMap for your requirement as suggested by hev1. But if you still want to make use of the Tuple class, then here is one way of doing it.
Add getter methods to your Tuple class
public class Tuple<A,B> {
public final A eventName;
public final B status;
public Tuple(A eventName, B status) {
this.eventName = eventName;
this.status = status;
}
public String toString() {
return "(" + eventName + ", " + status + ")";
}
public A getEventName() {
return eventName;
}
public B getStatus() {
return status;
}
}
Then collect all your tuples in a List and pass it to your setVariable method. Within this method just check if the given eventName is present in any of the tuples. If yes, then remove that Tuple from the list and create a new Tuple with the given status and add it back to the list. Something like this:
void setVariable(String eventName, String status, List<Tuple>tuples) {
boolean isRemoved = tuples.removeIf(tuple -> tuple.getEventName().equals(eventName));
if(isRemoved) {
Tuple tuple = new Tuple(eventName, status);
tuples.add(tuple);
}
}
Hope this helps.

(identifier expected) getter/setter and objects

I've got a problem with my programm. When i try to compile following i just receive the message:
Tutorium.java:15: error: <identifier> expected
public void settName(vorlesung.lectureName) {
^
So my Code:
Tutorium.java
public class Tutorium {
private Vorlesung vorlesung;
public String tName;
private int tNumber;
public int gettNumber() {
return this.tNumber;
}
public String gettName() {
return this.tName;
}
public void settName(vorlesung.lectureName) {
this.tName = vorlesung.lectureName;
}
public String toString() {
return (this.tName + ", " + this.tNumber);
}
public Tutorium(int tNumber){
this.tNumber = tNumber; } }
Vorlesung.java
public class Vorlesung {
public String lectureName;
private int lectureNumber;
private int lecture;
private Dozent dozent;
private String lecturerlName;
public String getlectureName(){
return this.lectureName;
}
public int lectureNumber(){
return this.lectureNumber;
}
public int lecture(){
return this.lecture;
}
public String getlecturer(){
this.lecturerlName = dozent.lecturerlName;
return this.lecturerlName;
}
public String toString() {
return (this.lectureName + ", " + this.lectureNumber);
}
public Vorlesung(String lectureName, int lecture) {
this.lectureName = lectureName;
this.lecture = lecture +1;
this.lectureNumber = this.lecture -1;
this.lecturerlName = lecturerlName;
}}
My Main-Method:
public class MainVorlesung {
public static void main(String[] args) {
Student student = new Student("STUDENTNAME", "STUDENTLASTNAME", 178, 1);
Vorlesung vorlesung = new Vorlesung("Programmieren", 13341);
Tutorium tutorium = new Tutorium(3);
Dozent dozent = new Dozent("LECTURERFIRSTNAME", "LECTURERLASTNAME", 815);
System.out.println(student.toString());
System.out.println(vorlesung.toString());
System.out.println(tutorium.toString());
System.out.println(dozent.toString());
}}
My goal is to set the value of tName equal the value of vorlesung.lectureName.
Why can't i do this that way?
I appreciate every help. :)
Thanks
For methods, the arguments that you pass in must have a declared value.
In this case, a String. So you need to change your method to this:
public void settName(String newLectureName) {
this.tName = newLectureName;
}
Read more about what a java method is and how to create one here: http://www.tutorialspoint.com/java/java_methods.htm
Change settName to
public void settName(String name) {
this.tName = name;
}
Since your goal is:
My goal is to set the value of tName equal the value of vorlesung.lectureName.
You should get rid of the setName method entirely since it will depend entirely on the vorlesung field and so should not be changeable. You should also get rid of the tName field, and instead change getName() to:
public class Tutorium {
private Vorlesung vorlesung;
// public String tName; // get rid of
private int tNumber;
public String gettName() {
if (vorlesung != null) {
return vorlesung.getlecturer();
}
return null; // or throw exception
}
// *** get rid of this since you won't be setting names
// public void settName(Vorlesung vorlesung) {
// this.tName = vorlesung.lectureName;
// }
I have just now noticed that your Tutorium class does not have and absolutely needs a setVorlesung(...) method.
public void setVorlesung(Vorlesung vorlesung) {
this.vorlesung = vorlesung;
}

The type of the expression must be an array type but it resolved to

Im new to java. I dont understand why these errors are occurring. trying to make an array list so that it saves each object. The errors im getting are The type of the expression must be an array type but it resolved to ArrayList on the line 'newbug1[i].setspecies();'
Thankyou in advance
import javax.swing.JOptionPane;
import java.util.ArrayList;
public class Abug2 {
private String species;
private String name;
private char symbol = '\0';
private int horposition = 0, verposition = 0, energy = 0, uniqueID = 1, counter;
public Abug2(String species, String name, char symbol)
{
uniqueID = counter;
counter++;
}
public void setspecies(){
species = JOptionPane.showInputDialog(null, "Enter the species: ");
}
public String getspecies(){
return species;
}
public void setname(){
name = JOptionPane.showInputDialog(null, "Enter the name: ");
}
public String getname(){
return name;
}
public void setsymbol(){
symbol = name.charAt(0);
}
public char getsymbol(){
return symbol;
}
public int getid(){
return uniqueID;
}
public int gethorizontal(){
return horposition;
}
public int getvertical(){
return verposition;
}
public int getenergy(){
return energy;
}
//The class ABug has a set of methods: two or more constructors, toString, toText, and getters and setters for the attributes
public String toString(){
String tostring = "\nName: " + name + "\nHorizontal Position: " + horposition + "\nVertical Position: " + verposition + "\n";
return tostring;
}
public String toText(){
String totext = getspecies() + getname() + getsymbol() + getid() + gethorizontal() + getvertical() + getenergy();
return totext;
}
public static void main (String [] args){
ArrayList<Abug2> newbug1 = new ArrayList<Abug2>();
String choice = JOptionPane.showInputDialog(null, "Would you like to add another bug?: ");
do{for (int i = 0; i < 3; i++) {
newbug1.add(new Abug2("Bug", "Spider", 's'));
newbug1[i].setspecies();
newbug1[i].setname();
newbug1[i].setsymbol();
System.out.println(newbug1[i].toString());
} }while(choice != "yes");
}
}
For arraylists use get() instead:
newbug1.get(i).setspecies();
newbug1.get(i).setname();
newbug1.get(i).setsymbol();
Because it stores object references any setFoo calls affect the original object referenced in the arraylist.
In order to access an element in an ArrayList you have to use a method called get.
In your code, replace newbug1[i] by newbug1.get(i)
And moreover, you should store that reference in a variable instead of recalling it again and again:
Abug2 currentBug = newbug1.get(i);
currentBug.setSpecies();
Your code will gain in clarity.

Using Enum values as String literals

What is the best way to use the values stored in an Enum as String literals?
For example:
public enum Modes {
some-really-long-string,
mode1,
mode2,
mode3
}
Then later I could use Mode.mode1 to return its string representation as mode1. Without having to keep calling Mode.mode1.toString().
You can't. I think you have FOUR options here. All four offer a solution but with a slightly different approach...
Option One: use the built-in name() on an enum. This is perfectly fine if you don't need any special naming format.
String name = Modes.mode1.name(); // Returns the name of this enum constant, exactly as declared in its enum declaration.
Option Two: add overriding properties to your enums if you want more control
public enum Modes {
mode1 ("Fancy Mode 1"),
mode2 ("Fancy Mode 2"),
mode3 ("Fancy Mode 3");
private final String name;
private Modes(String s) {
name = s;
}
public boolean equalsName(String otherName) {
// (otherName == null) check is not needed because name.equals(null) returns false
return name.equals(otherName);
}
public String toString() {
return this.name;
}
}
Option Three: use static finals instead of enums:
public final class Modes {
public static final String MODE_1 = "Fancy Mode 1";
public static final String MODE_2 = "Fancy Mode 2";
public static final String MODE_3 = "Fancy Mode 3";
private Modes() { }
}
Option Four: interfaces have every field public, static and final:
public interface Modes {
String MODE_1 = "Fancy Mode 1";
String MODE_2 = "Fancy Mode 2";
String MODE_3 = "Fancy Mode 3";
}
Every enum has both a name() and a valueOf(String) method. The former returns the string name of the enum, and the latter gives the enum value whose name is the string. Is this like what you're looking for?
String name = Modes.mode1.name();
Modes mode = Modes.valueOf(name);
There's also a static valueOf(Class, String) on Enum itself, so you could also use:
Modes mode = Enum.valueOf(Modes.class, name);
You could override the toString() method for each enum value.
Example:
public enum Country {
DE {
#Override
public String toString() {
return "Germany";
}
},
IT {
#Override
public String toString() {
return "Italy";
}
},
US {
#Override
public String toString() {
return "United States";
}
}
}
Usage:
public static void main(String[] args) {
System.out.println(Country.DE); // Germany
System.out.println(Country.IT); // Italy
System.out.println(Country.US); // United States
}
As Benny Neugebauer mentions, you could overwrite the toString(). However instead overwriting the toString for each enum field I like more something like this:
public enum Country{
SPAIN("EspaƱa"),
ITALY("Italia"),
PORTUGAL("Portugal");
private String value;
Country(final String value) {
this.value = value;
}
public String getValue() {
return value;
}
#Override
public String toString() {
return this.getValue();
}
}
You could also add a static method to retrieve all the fields, to print them all, etc.
Simply call getValue to obtain the string associated to each Enum item
mode1.name() or String.valueOf(mode1). It doesn't get better than that, I'm afraid
public enum Modes {
MODE1("Mode1"),
MODE2("Mode2"),
MODE3("Mode3");
private String value;
public String getValue() {
return value;
}
private Modes(String value) {
this.value = value;
}
}
you can make a call like below wherever you want to get the value as a string from the enum.
Modes.MODE1.getvalue();
This will return "Mode1" as a String.
For my enums I don't really like to think of them being allocated with 1 String each. This is how I implement a toString() method on enums.
enum Animal
{
DOG, CAT, BIRD;
public String toString(){
switch (this) {
case DOG: return "Dog";
case CAT: return "Cat";
case BIRD: return "Bird";
}
return null;
}
}
You can use Mode.mode1.name() however you often don't need to do this.
Mode mode =
System.out.println("The mode is "+mode);
As far as I know, the only way to get the name would be
Mode.mode1.name();
If you really need it this way, however, you could do:
public enum Modes {
mode1 ("Mode1"),
mode2 ("Mode2"),
mode3 ("Mode3");
private String name;
private Modes(String s) {
name = s;
}
}
my solution for your problem!
import java.util.HashMap;
import java.util.Map;
public enum MapEnumSample {
Mustang("One of the fastest cars in the world!"),
Mercedes("One of the most beautiful cars in the world!"),
Ferrari("Ferrari or Mercedes, which one is the best?");
private final String description;
private static Map<String, String> enumMap;
private MapEnumSample(String description) {
this.description = description;
}
public String getEnumValue() {
return description;
}
public static String getEnumKey(String name) {
if (enumMap == null) {
initializeMap();
}
return enumMap.get(name);
}
private static Map<String, String> initializeMap() {
enumMap = new HashMap<String, String>();
for (MapEnumSample access : MapEnumSample.values()) {
enumMap.put(access.getEnumValue(), access.toString());
}
return enumMap;
}
public static void main(String[] args) {
// getting value from Description
System.out.println(MapEnumSample.getEnumKey("One of the fastest cars in the world!"));
// getting value from Constant
System.out.println(MapEnumSample.Mustang.getEnumValue());
System.out.println(MapEnumSample.getEnumKey("One of the most beautiful cars in the world!"));
System.out.println(MapEnumSample.Mercedes.getEnumValue());
// doesnt exist in Enum
System.out.println("Mustang or Mercedes, which one is the best?");
System.out.println(MapEnumSample.getEnumKey("Mustang or Mercedes, which one is the best?") == null ? "I don't know!" : "I believe that "
+ MapEnumSample.getEnumKey("Ferrari or Mustang, which one is the best?") + " is the best!.");
// exists in Enum
System.out.println("Ferrari or Mercedes, wich one is the best?");
System.out.println(MapEnumSample.getEnumKey("Ferrari or Mercedes, which one is the best?") == null ? "I don't know!" : "I believe that "
+ MapEnumSample.getEnumKey("Ferrari or Mercedes, which one is the best?") + " is the best!");
}
}
You can simply use:
""+ Modes.mode1
public enum Environment
{
PROD("https://prod.domain.com:1088/"),
SIT("https://sit.domain.com:2019/"),
CIT("https://cit.domain.com:8080/"),
DEV("https://dev.domain.com:21323/");
private String url;
Environment(String envUrl) {
this.url = envUrl;
}
public String getUrl() {
return url;
}
}
String prodUrl = Environment.PROD.getUrl();
It will print:
https://prod.domain.com:1088/
This design for enum string constants works in most of the cases.
Enum is just a little bit special class. Enums can store additional fields, implement methods etc. For example
public enum Modes {
mode1('a'),
mode2('b'),
mode3('c'),
;
char c;
private Modes(char c) {
this.c = c;
}
public char character() {
return c;
}
}
Now you can say:
System.out.println(Modes.mode1.character())
and see output:
a
package com.common.test;
public enum Days {
monday(1,"Monday"),tuesday(2,"Tuesday"),wednesday(3,"Wednesday"),
thrusday(4,"Thrusday"),friday(5,"Friday"),saturday(6,"Saturday"),sunday(7,"Sunday");
private int id;
private String desc;
Days(int id,String desc){
this.id=id;
this.desc=desc;
}
public static String getDay(int id){
for (Days day : Days.values()) {
if (day.getId() == id) {
return day.getDesc();
}
}
return null;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
};
This method should work with any enum:
public enum MyEnum {
VALUE1,
VALUE2,
VALUE3;
public int getValue() {
return this.ordinal();
}
public static DataType forValue(int value) {
return values()[value];
}
public String toString() {
return forValue(getValue()).name();
}
}
i found this one is more easy for preventing type error:
public enum Modes {
some-really-long-string,
mode1,
mode2,
mode3;
String str;
Modes(){
this.str = super.name();
}
#Override
#NonNull
public String toString() {
return str;
}
however - this may work when you need to use a String on a log/println or whenever java compiles the toString() method automatically, but on a code line like this ->
// sample method that require (string,value)
intent.putExtra(Modes.mode1 ,shareElement.getMode()); // java error
// first argument enum does not return value
instead as mentioned above you will still have to extend the enum and use .name() in those cases like this:
intent.putExtra(Modes.mode1.name() ,shareElement.getMode());
after many tries I have come with this solution
public static enum Operation {
Addition, Subtraction, Multiplication, Division,;
public String getUserFriendlyString() {
if (this==Addition) {
return " + ";
} else if (this==Subtraction) {
return " - ";
} else if (this==Multiplication) {
return " * ";
} else if (this==Division) {
return " / ";
}
return "undefined";
}
}
You can try this:
public enum Modes {
some-really-long-string,
mode1,
mode2,
mode3;
public String toString(){
switch(this) {
case some-really-long-string:
return "some-really-long-string";
case mode2:
return "mode2";
default: return "undefined";
}
}
}
use mode1.name() or String.valueOf(Modes.mode1)

Categories

Resources