I want to improve my use of JDK 1.5 and stop using private static final String instead of enum. This is what seems to be recommended.
But now my constant class looks like this :
public class CEnum{
/**
* #author JJA
* date : 20/10/2010
*/
public enum ListTypeAffichage {
DEP("DEPOT_TVA"), PAD("PAS_DEPOT_TVA"), NORM("CAT_NORMALE"), CAP("CAT_PARTICULIERE"), CAA("CAT_AUTRE_CAS");
private final String sName;
/**
* #param name String
*/
ListTypeAffichage(String name) {
this.sName = name;
}
/**
* #return String
*/
public String getType() {
return sName;
}
}
/**
* #author JJA
* date : 20/10/2010
*/
public enum ListTypeCategorie {
DEDUIRE("SOMME_A_DEDUIRE"), AJOUTER("SOMME_A_AJOUTER");
private final String sName;
/**
* #param name String
*/
ListTypeCategorie(String name) {
this.sName = name;
}
/**
* #return String
*/
public String getType() {
return sName;
}
}
/**
* #author JJA
* date : 26/10/2010
*/
public enum ListInterval {
POS("POSITIF"), NS("NON_SIGNE");
private final String sName;
/**
* #param name String
*/
ListInterval(String name) {
this.sName = name;
}
/**
* #return String
*/
public String getInterval() {
return sName;
}
}
}
instead of
public class ConstantesADMD {
public static final List<String> typeAffich = new ArrayList<String>();
...
ConstantesADMD(){
typeAffich.add("DEPOT_TVA");
typeAffich.add("PAS_DEPOT_TVA");
typeAffich.add("CAT_NORMALE");
...
}
}
My code seems to be really bad, but at least works. For each enum I have to add the redundant code :
private final String sName;
/**
* #param name String
*/
ListTypeAffichage(String name) {
this.sName = name;
}
/**
* #return String
*/
public String getType() {
return sName;
}
What improvment do you advise me?
Note : forget the last sentences of my first question, I need the index. Tell me if I have to post another question, editing my fisrt seems easier.
I would name my enum-constants as you have named your strings. You can then access the name using the Enum.toString() method. For example:
public enum ListTypeAffichage {
DEPOT_TVA, PAS_DEPOT_TVA, CAT_NORMALE, CAT_PARTICULIERE, CAT_AUTRE_CAS;
/**
* #return String
*/
public String getType() {
return toString();
}
}
You could of course also skip the getType() all together, and access the "type" using toString() instead:
ListTypeAffichage myEnum = ListTypeAffichage.CAT_PARTICULIRE;
System.out.println("Type: " + myEnum.toString()); // like this...
System.out.println("Type: " + myEnum); // ...or like this
According to the API, this is better than using the Enum.name() directly:
public final String name()
[...] Most programmers should use the toString() method in preference to this one [...]
Each enum has a name() method which return the exact string represantation of the constant. So you may do this:
public enum ListTypeAffichage {
DEPOT_TVA, PAS_DEPOT_TVA, CAT_NORMALE, CAT_PARTICULIERE, CAT_AUTRE_CAS
}
and then
ListTypeAffichage.DEPOT_TVA.name();
By using the abbreviations (DEP, PAD, NORM) etc. you have created aliases to (DEPOT_TVA, PAS_DEPOT_TVA, CAT_NORMALE) etc.
If you want to keep the abbreviations, then you'll have to maintain the enum as you have it.
If you are willing to do away with the abbreviations, then you can change you enum as below, I have included a main method in the enum to demonstrate its use.
public enum ListTypeAffichageNames {
DEPOT_TVA,
PAS_DEPOT_TVA,
CAT_NORMALE,
CAT_PARTICULIERE,
CAT_AUTRE_CAS;
public static void main(String[] args) {
System.out.println(DEPOT_TVA.toString());
ListTypeAffichageNames affichage = ListTypeAffichageNames.valueOf("DEPOT_TVA");
System.out.println(affichage.toString());
}
}
In addition to this, your current structure of constants does not give you compile time type checking, and does not prevent something like the following happening during runtime:
ConstantesADMD.typeAffich.clear();
// or
ConstantesADMD.typeAffich.remove("DEPOT_TVA");
ConstantesADMD.typeAffich.add("dEpOt-tVa");
Related
Can't resolve the problem :\ How i should document the second parameter "says"? Because SonarQube asking me about this again and again.
public class Dogs {
private static final org.slf4j.Logger LOGGER = LoggerFactory.getLogger(Dogs.class);
private final String name;
private final String says;
/**
* The Dogs class.
*
* #param name
* says. // here the problem
*
*/
public Dogs(final String name, final String says) {
this.name = name;
this.says = says;
}
}
You should add #param in front of the param name, like this :
/**
* The Dogs class.
*
* #param name explain what is it !
* #param says explain what is it !
*
*/
public Dogs(final String name, final String says) {
this.name = name;
this.says = says;
}
Given a string i want to get the enum equivalent of it in constant time.
I have a enum defined like the one shown in the question. Best way to create enum of strings?
public enum Strings {
STRING_ONE("ONE"),
STRING_TWO("TWO")
;
private final String text;
/**
* #param text
*/
private Strings(final String text) {
this.text = text;
}
/* (non-Javadoc)
* #see java.lang.Enum#toString()
*/
#Override
public String toString() {
return text;
}
}
If i now get a string (say "TWO"), is there a way to see if it exists and if it exists then is there a way i can define a method that will return the enum value (for example if i pass "TWO", i should be getting back "Strings.STRING_TWO"?
Is Enum.valueOf() not sufficient? How would you imagine being more efficient than that? There's (usually) no need to have an enum STRING_ONE("ONE") - just call enum value ONE and you get .valueOf() lookup for free.
Otherwise, just create a private static Map<String, YourEnum> and provide a similar valueOf() method that looks up against the Map.
Since Enum.valueOf operates on the built-in name of the enum (i.e. "STRING_ONE" and "STRING_TWO") you would need to roll your own "registry" of name-to-enum, like this:
public enum Strings {
STRING_ONE("ONE"),
STRING_TWO("TWO")
;
private static final Map<String,Strings> byName = new HashMap<String,Strings>();
private final String text;
private Strings(final String text) {
this.text = text;
}
static {
for (Strings s : Strings.values()) {
byName.put(s.toString(), s);
}
}
#Override
public String toString() {
return text;
}
public static Strings forName(String name) {
return byName.get(name);
}
}
Demo.
Above, a map from string name to enum Strings is used to do the translation. If the name is not there, null would be returned from the Strings.forName method.
I think you need to change the code to be :
public enum Strings {
STRING_ONE("ONE"), STRING_TWO("TWO");
private String text;
/**
* #param text
*/
private Strings(final String text) {
this.text = text;
}
public String getText() {
return this.text;
}
public static Strings getByTextValue(String text) {
for (Strings str : Strings.values()) {
if (str.getText().equals(text)) {
return str;
}
}
return null;
}
/*
* (non-Javadoc)
*
* #see java.lang.Enum#toString()
*/
#Override
public String toString() {
return text;
}
}
Example :
String test = "ONE";
Strings testEnum = Strings.getByTextValue(test);
now you have testEnum which is enum reference
To be clear, this is an active homework assignment. I just need some guidance.
I am creating a bookstore program in Java that, in revision 1, only has to return information about one specific book when it runs. I must use two classes, and call the info in the secondary class inside the main method to output.
I think I created the constructor correctly inside the Book class, but what's the best way to A) define those variables and B) call the info inside the Bookstore class to output? I just need some guidance here, as I'm kinda stuck. Eclipse is asking me to re-define the int and double variables as a String, but they are going to be numbers...is there something in my syntax that is causing it to do that?
Here's what I have so far:
import java.util.Scanner; // Import Scanner
/** Main Class */
public class Bookstore {
/** Secondary Class */
private class Book {
/** Declare Variables */
private int isbn;
private String bookTitle;
private String authorName;
private int yearPublished;
private String publisherName;
private double bookPrice;
/** Constructor */
Book (int isbn, String bookTitle, String authorName, int yearPublished, String publisherName, double bookPrice) {
setIsbn(isbn);
setBookTitle(bookTitle);
setAuthorName(authorName);
setYearPublished(yearPublished);
setPublisherName(publisherName);
setBookPrice(bookPrice);
}
/**
* #return the isbn
*/
public void getIsbn(int isbn) {
return isbn;
}
/**
* #param isbn the isbn to set
*/
public void setIsbn(int isbn) {
this.isbn = isbn;
}
/**
* #return the bookTitle
*/
public void getBookTitle(String bookTitle) {
return bookTitle;
}
/**
* #param bookTitle the bookTitle to set
*/
public void setBookTitle(String bookTitle) {
this.bookTitle = bookTitle;
}
/**
* #return the authorName
*/
public String getAuthorName() {
return authorName;
}
/**
* #param authorName the authorName to set
*/
public void setAuthorName(String authorName) {
this.authorName = authorName;
}
/**
* #return the yearPublished
*/
public int getYearPublished() {
return yearPublished;
}
/**
* #param yearPublished the yearPublished to set
*/
public void setYearPublished(int yearPublished) {
this.yearPublished = yearPublished;
}
/**
* #return the publisherName
*/
public String getPublisherName() {
return publisherName;
}
/**
* #param publisherName the publisherName to set
*/
public void setPublisherName(String publisherName) {
this.publisherName = publisherName;
}
/**
* #return the bookPrice
*/
public double getBookPrice() {
return bookPrice;
}
/**
* #param bookPrice the bookPrice to set
*/
public void setBookPrice(double bookPrice) {
this.bookPrice = bookPrice;
}
} // End Book Class
/** Main Method */
public static void main(String[] args) {
} // End Main Method
} // End Bookstore Class
That's where I'm at. Again, I'm stuck on how to define the variables properly, and then call the data for output in the Bookstore method. I know how to print it to the screen, it's just getting it there that is perplexing me. Do I create another Book object inside the Bookstore class?
I appreciate any help that's available.
Let's start with...
private class Book {
I would say declaring an inner class as private might not be the best choice, as you not be able to use beyond the scope of BookStore, but that's a choice you need to make...
This...
/**
* #return the isbn
*/
public void getIsbn(int isbn) {
return isbn;
}
is wrong on a number of accounts. First, it is declared as void, meaning that the method won't return anything, but then you use return isbn within the method. It should be declared as returning an int.
Next, you pass isbn as a parameter to the method, but immediately return the same value, this isn't really what you want to do, you want to return the value of isbn defined by Book, for example...
/**
* #return the isbn
*/
public int getIsbn() {
return isbn;
}
The same thing goes for getBookTitle.
In some languages they pass parameters by reference, meaning you can actually alter the value in the method/function and that will be reflected in the callers context. Java doesn't do this (more accurately, you can't reassign the value within the method and have it reflected in the caller). This is tripping point for many developers.
Basically, this means you can't do something like...
public void getBookTitle(String bookTitle) {
bookTitle = this.bookTitle;
}
As the value of the parameter will the same in the callers context after the method call as it was before it. You have to "get" the value from the class.
An interesting side effect though, is you can change the properties of objects passed to a method, if they supply mutable functionality...
I am trying to instantiate an object from the following class:
public class Name {
//The unmodified name
private String name;
//The modified name
private String preprocessedName;
/**
* Constructor method which stores the original name in the name variable
* #param inputName
*/
public Name(String inputName){
//Store the name
this.name = inputName;
//Initialise the preProcessedName
this.preprocessedName = null;
}
/**
* Retrieves the original name
* #return the original name
*/
public String getName(){
return this.name;
}
/**
* Stores the preprocessed name in the preprocessedName variable
* #param the preprocessed name
*/
public void setPreprocessedName(String processedInput){
this.preprocessedName = processedInput;
}
/**
* Retrieves the preprocessed name
* #return the preprocessed name
*/
public String getpreprocessedName(){
return this.preprocessedName;
}
}
Within the following method:
/**
* Private method which instantiates names as a name object.
* #param names
*/
private void processInput(ArrayList<String> names){
library = new ArrayList<Name>();
for(String name : names){
Name tempName = new Name("r");
//Not bringing up any methods from the class
**strong text**tempName.**strong text**
//add to the library
library.add(tempName);
}
}
I am unable to use any methods from the Name class when I create the object, do you know why this is happening? e.g. it does not bring up the getters and setters from the class when I try auto completion.
Check the imports you have in the package.
Are you importing the correct Name class?
What is the best way to have a enum type represent a set of strings?
I tried this:
enum Strings{
STRING_ONE("ONE"), STRING_TWO("TWO")
}
How can I then use them as Strings?
I don't know what you want to do, but this is how I actually translated your example code....
package test;
/**
* #author The Elite Gentleman
*
*/
public enum Strings {
STRING_ONE("ONE"),
STRING_TWO("TWO")
;
private final String text;
/**
* #param text
*/
Strings(final String text) {
this.text = text;
}
/* (non-Javadoc)
* #see java.lang.Enum#toString()
*/
#Override
public String toString() {
return text;
}
}
Alternatively, you can create a getter method for text.
You can now do Strings.STRING_ONE.toString();
Custom String Values for Enum
from http://javahowto.blogspot.com/2006/10/custom-string-values-for-enum.html
The default string value for java enum is its face value, or the element name. However, you can customize the string value by overriding toString() method. For example,
public enum MyType {
ONE {
public String toString() {
return "this is one";
}
},
TWO {
public String toString() {
return "this is two";
}
}
}
Running the following test code will produce this:
public class EnumTest {
public static void main(String[] args) {
System.out.println(MyType.ONE);
System.out.println(MyType.TWO);
}
}
this is one
this is two
Use its name() method:
public class Main {
public static void main(String[] args) throws Exception {
System.out.println(Strings.ONE.name());
}
}
enum Strings {
ONE, TWO, THREE
}
yields ONE.
Either set the enum name to be the same as the string you want or, more generally,you can associate arbitrary attributes with your enum values:
enum Strings {
STRING_ONE("ONE"), STRING_TWO("TWO");
private final String stringValue;
Strings(final String s) { stringValue = s; }
public String toString() { return stringValue; }
// further methods, attributes, etc.
}
It's important to have the constants at the top, and the methods/attributes at the bottom.
Depending on what you mean by "use them as Strings", you might not want to use an enum here. In most cases, the solution proposed by The Elite Gentleman will allow you to use them through their toString-methods, e.g. in System.out.println(STRING_ONE) or String s = "Hello "+STRING_TWO, but when you really need Strings (e.g. STRING_ONE.toLowerCase()), you might prefer defining them as constants:
public interface Strings{
public static final String STRING_ONE = "ONE";
public static final String STRING_TWO = "TWO";
}
You can use that for string Enum
public enum EnumTest {
NAME_ONE("Name 1"),
NAME_TWO("Name 2");
private final String name;
/**
* #param name
*/
private EnumTest(final String name) {
this.name = name;
}
public String getName() {
return name;
}
}
And call from main method
public class Test {
public static void main (String args[]){
System.out.println(EnumTest.NAME_ONE.getName());
System.out.println(EnumTest.NAME_TWO.getName());
}
}
If you do not want to use constructors, and you want to have a special name for the method, try it this:
public enum MyType {
ONE {
public String getDescription() {
return "this is one";
}
},
TWO {
public String getDescription() {
return "this is two";
}
};
public abstract String getDescription();
}
I suspect that this is the quickest solution. There is no need to use variables final.
Get and set with default values.
public enum Status {
STATUS_A("Status A"), STATUS_B("Status B"),
private String status;
Status(String status) {
this.status = status;
}
public String getStatus() {
return status;
}
}