This question already has answers here:
Generating Enums Dynamically
(4 answers)
Closed 2 years ago.
I'm trying to create an Enumeration in Java. I did a code I created a comboBox with the enum values and it was correct. The problem is that in that case I knew the values I wanted ComboBox to have.
Now I'm trying to create a ComboBox in SceneBuilder with an object characteristic.
I receive from a file a lot of tasks and all of them have it own reference. I want to create an enum with all the references with the objective that user chose one task from the reference in the ComboBox.
Here is the Task code in portuguese (referencia means reference):
//This is a constructor of Tarefa (task):
public Tarefa(String referencia, String designacao, String descricaoInformal, String descricaoTecnica, int duracaoEstimada, Double custoEstimado) {
this.referencia = referencia;
this.designacao = designacao;
this.descricaoInformal = descricaoInformal;
this.descricaoTecnica = descricaoTecnica;
this.duracaoEstimada = duracaoEstimada;
this.custoEstimado = custoEstimado;
}
public String getReferencia() {
return referencia;
}
I was creating other JavaClass creating something like this:
public enum Prioridade {
BAIXA {
public String toString() {
return "Baixa";
}
},
ABAIXO_NORMAL {
public String toString() {
return "Abaixo do Normal";
}
},
NORMAL {
public String toString() {
return "Normal";
}
},
ACIMA_NORMAL {
public String toString() {
return "Acima do Normal";
}
},
ELEVADO {
public String toString() {
return "Elevado";
}
},
TEMPO_REAL {
public String toString() {
return "Tempo Real";
}
};
}
But in that case I knew the values I wanted enum to have.
How can I create an Enum not knowing from the beggining the values it will have? I only know the type: String.
You can use static method of enum valueOf(String str)
For example Prioridade.valueOf("ACIMA_NORMAL")
Related
This question already has answers here:
C# vs Java Enum (for those new to C#)
(13 answers)
Is it possible to add custom properties to c# enum object?
(2 answers)
Closed 2 years ago.
I have a very basic question. In Java, it is possible to point attributes and variables to Enums, such as:
public enum DayTime{
Morning("Morning"),
Afternoon("Afternoon"),
Night("Night");
private string description;
Daytime(string description){
this.description = description;
}
public string getDescription(){
return description;
}
}
Is it possible to apply the same concept to C#? I am trying to get modular descriptions to products, whereas their name, contents and characteristics would be shown in a string of text, and Enums looked like the best alternative to modify this text according to which characteristic is selected.
C# enums are very basic compared to Java enums. If you want to simulate the same kind of behavior you need to use a class with an inner enum:
using System.Collections.Generic;
public sealed class DayTime
{
public static readonly DayTime Morning = new DayTime("Morning", InnerEnum.Morning);
public static readonly DayTime Afternoon = new DayTime("Afternoon", InnerEnum.Afternoon);
public static readonly DayTime Night = new DayTime("Night", InnerEnum.Night);
private static readonly List<DayTime> valueList = new List<DayTime>();
static DayTime()
{
valueList.Add(Morning);
valueList.Add(Afternoon);
valueList.Add(Night);
}
//the inner enum needs to be public for use in 'switch' blocks:
public enum InnerEnum
{
Morning,
Afternoon,
Night
}
public readonly InnerEnum innerEnumValue;
private readonly string nameValue;
private readonly int ordinalValue;
private static int nextOrdinal = 0;
private string description;
internal DayTime(string name, InnerEnum innerEnum)
{
this.description = name;
nameValue = name;
ordinalValue = nextOrdinal++;
innerEnumValue = innerEnum;
}
public string Description
{
get
{
return description;
}
}
//the following methods reproduce Java built-in enum functionality:
public static DayTime[] values()
{
return valueList.ToArray();
}
public int ordinal()
{
return ordinalValue;
}
public override string ToString()
{
return nameValue;
}
public static DayTime valueOf(string name)
{
foreach (DayTime enumInstance in DayTime.valueList)
{
if (enumInstance.nameValue == name)
{
return enumInstance;
}
}
throw new System.ArgumentException(name);
}
}
Given this complexity, it may be best to rewrite your logic in a way that's more natural for C# without using enums.
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.
This question already has answers here:
Can someone explain to me in detail the use of 'this'?
(9 answers)
Closed 9 years ago.
I'm able to learn and pick up things very fast, but this is still confusing me:
This is in the main class (DCFlags):
private WGCustomFlagsPlugin pluginWGCustomFlags;
private WorldGuardPlugin pluginWorldGuard;
private DCPvPToggle pluginDCPvPToggle;
private RegionListener listener;
public WGCustomFlagsPlugin getWGCFP(){
return this.pluginWGCustomFlags;
}
public WorldGuardPlugin getWGP() {
return this.pluginWorldGuard;
}
public DCPvPToggle getPPT(){
return this.pluginDCPvPToggle;
}
public void onEnable(){
this.pluginWorldGuard = Utils.getWorldGuard(this);
this.pluginWGCustomFlags = Utils.getWGCustomFlags(this);
this.pluginDCPvPToggle = Utils.getDCPvPToggle(this);
this.listener = new RegionListener(this);
}
This in a different class (Utils):
public static WGCustomFlagsPlugin getWGCustomFlags(DCFlags plugin){
Plugin wgcf = plugin.getServer().getPluginManager().getPlugin("WGCustomFlags");
if ((wgcf == null) || (!(wgcf instanceof WGCustomFlagsPlugin))) {
return null;
}
return (WGCustomFlagsPlugin)wgcf;
}
public static WorldGuardPlugin getWorldGuard(DCFlags plugin){
Plugin wg = plugin.getServer().getPluginManager().getPlugin("WorldGuard");
if ((wg == null) || (!(wg instanceof WorldGuardPlugin))) {
return null;
}
return (WorldGuardPlugin)wg;
}
public static DCPvPToggle getDCPvPToggle(DCFlags plugin){
Plugin ppt = plugin.getServer().getPluginManager().getPlugin("DCPvPToggle");
if ((ppt == null) || (!(ppt instanceof DCPvPToggle))) {
return null;
}
return (DCPvPToggle)ppt;
}
I know this is for being able to use methods from other plugins, but what is "this." for and why is it needed?
this is always a reference to the current object.
In these examples it's not needed. However, consider the following:
class C {
private String name;
public void setName(String name) {
this.name = name;
}
}
In this case, the this keyword serves to differentiate between the local variable name, passed to the setName method, and the field this.name, which is declared in the class.
Also consider the following:
class C {
private String name;
public void doSomething(final String name) {
// here, `this` is an instance of C
new Runnable() {
#Override
public void run() {
// here, `this` is an instance of Runnable
System.out.println(name);
// prints the name passed to the method
System.out.println(this.name);
// error: Runnable has no field name
System.out.println(C.this.name);
// prints the enclosing class's name
}
}.run();
}
}
In some other languages, such as Python, it is always required to use self. (the rough semantic equivalent of this.) to refer to a field. In Java, it is not.
This question already has answers here:
How to retrieve Enum name using the id?
(11 answers)
Closed 9 years ago.
I need to do look up in an enum by an int . The enum is as folows :
public enum ErrorCode{
MissingReturn(1,"Some long String here"),
InvalidArgument(2,"Another long String here");
private final int shortCode ;
private final String detailMessage;
ErrorCode(shortCode ,detailMessage){
this.shortCode = shortCode ;
this.detailMessage= detailMessage;
}
public String getDetailedMessage(){
return this.detailMessage;
}
public int getShortCode(){
return this.shortCode ;
}
}
Now Is need to have a lookup method that would take an int code and should return me the String message pertaining to that code that is stored in the Enum.Passing a "1" should return me the String "Some long String here". What is the best way to implement this functionality?
public static String lookUpMessageFromCode(int code){
}
P.S: Is the class EnumMap useful for this kind of use case? If yes,please let me know why?
Depending on the int values that you associated with your enum, I would add a static array of ErrorCodes, or a static Map<Integer,ErrorCode> to your enum class, and use it to do a lookup in the message from code method. In your case, an array is more appropriate, because you have values 1 and 2 which are small. I would also change the signature to return ErrorCode.
private static final ErrorCode[] allErrorCodes = new ErrorCode[] {
null, MissingReturn, InvalidArgument
};
public static ErrorCode lookUpByCode(int code) {
// Add range checking to see if the code is valid
return allErrorCodes[code];
}
The callers who need the message would obtain it like this:
String message = ErrorCode.lookUpByCode(myErrorCode).getDetailedMessage();
I would simply iterate through your Enum values and check the code. This solution lets you utilize the existing Enum with out creating another object to manage.
public enum ErrorCode {
MissingReturn(1, "Some long String here"),
InvalidArgument(2, "Another long String here");
private final int shortCode;
private final String detailMessage;
ErrorCode(int shortCode, String detailMessage) {
this.shortCode = shortCode;
this.detailMessage = detailMessage;
}
public String getDetailedMessage() {
return this.detailMessage;
}
public int getShortCode() {
return this.shortCode;
}
public static String lookUpMessageFromCode(int code) {
String message = null;
for (ErrorCode errorCode : ErrorCode.values()) {
if (errorCode.getShortCode() == code) {
message = errorCode.getDetailedMessage();
break;
}
}
return message;
}
public static void main(String[] args) {
System.out.println(ErrorCode.lookUpMessageFromCode(1));
System.out.println(ErrorCode.lookUpMessageFromCode(2));
}
}
One thing to note
The Enum constructor is missing the type information regarding its parameters.
ErrorCode(int shortCode, String detailMessage) {
this.shortCode = shortCode;
this.detailMessage = detailMessage;
}
Here is another option:
public static String lookUpMessageFromCode(int code){
for(ErrorCode ec:ErrorCode.values()){
if(ec.shortCode==code)
return ec.detailMessage;
}
return null;
}
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()));