enum does not provide expected result - java

I have defined an enum in a class A
public class A{
public static final String CANDY = "yelow candy";
public static final String CAKE = "cookie";
public enum Yummy{
CANDY, CAKE;
}
}
In another package,
public class C {
Yummy[] yummies = A.Yummy.values();
for (Yummy yum : yummies){
String yumString = yum.toString();
System.out.println("yum =" + yumString);
}
}
I get CANDY and CAKE as a result, not "yelow candy" and "cookie".
What does I need to change to get the "yelow candy" and "cookie ?

You've defined an enum "A.Yummy" and also two strings, "A.Candy" and "A.CAKE".
They aren't linked at all.
You will want to delete the strings and add something like https://stackoverflow.com/a/13291109/1041364
public enum Yummy {
CANDY("yelow candy"),
CAKE("cookie");
private String description;
private Yummy(String description) {
this.description= description;
}
public String toString() {
return this.description;
}
}

Try the following:
public enum Yummy{
CANDY ("yellow candy"), CAKE ("cookie");
private String name;
private Yummy(String name) {
this.name = name;
}
public String toString() {
return this.name;
}
}

Additional values for enums should be hold in properties. You have to provide constructor to set up those properties.
public enum Yummy {
CANDY("yelow candy"), CAKE("cookie");
private String value;
private Yummy(String value) {
this.value = value;
}
};
And then in code you can use CANDY.value or override toString() method.

Try this:
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
for (Yummy yum : Yummy.values()) {
System.out.printf("%s, %s\n", yum, yum.getValue());
}
}
}
enum Yummy {
CANDY("yelow candy"),
CAKE("cookie");
private String value;
private Yummy(String value) {
this.value = value;
}
public String getValue() {
return this.value;
}
}

Related

Returning a string literal from an Enum

I'm trying to use an Enum to set a finite list of possible distances, with the string being used as a cssSelector within a Selenium API method:
public enum DistanceFrom {
FIVEMILES("a[data-reactid='.2cr8yg16ohc.2.1.0.2:$5.0']"),
TENMILES("a['.2cr8yg16ohc.2.1.0.2:$10.0.2']"),
TWENTYMILES("a['.2cr8yg16ohc.2.1.0.2:$20.0']"),
THIRTYMILES("a['.2cr8yg16ohc.2.1.0.2:$30.0']");
private String value;
DistanceFrom(String value){
this.value=value;
}
#Override
public String toString(){
return value;
}
}
I use this in a test:
local.setDistance(DistanceFrom.FIVEMILES.toString());
In which setDistance is a fluent method within a page object:
public LocalNewsPage setDistance(String value) {
WebElement setDistanceButton = driver.findElement(By.cssSelector(value));
setDistanceButton.click();
return this;
}
Why must I declare:
local.setDistance(DistanceFrom.FIVEMILES.toString());
And not be able to simply:
local.setDistance(DistanceFrom.FIVEMILES);
If you can edit the setDistance method, you can change it to accept a DistanceFrom:
public LocalNewsPage setDistance(DistanceFrom value) {
WebElement setDistanceButton = driver.findElement(By.cssSelector(value.toString()));
setDistanceButton.click();
return this;
}
Alternatively, you can change the enum values in DistanceFrom to static final Strings:
public final class DistanceFrom {
public static final String FIVEMILES = "a[data-reactid='.2cr8yg16ohc.2.1.0.2:$5.0']";
public static final String TENMILES = "a['.2cr8yg16ohc.2.1.0.2:$10.0.2']";
public static final String TWENTYMILES = "a['.2cr8yg16ohc.2.1.0.2:$20.0']";
public static final String THIRTYMILES = "a['.2cr8yg16ohc.2.1.0.2:$30.0']";
private DistanceFrom() {}
}

How to change the value of private variable in java

I started to programm in Java since Yesterday, and I have the biggest question of my entire programmer life(since Yesterday).
For example, let's say I have a code like this:
public class itsAClass {
static private String A;
public static void main() {
A = "This should be changed";
}
public String something() {
return A;
}
}
I wanted to use the method something() in another Class to get the String Sentence of A, but I got only null.
How can I change the value of A, so that the another Class can get the Value "This should be changed"?
If you just want to bring this code to work you just can make something() static as well.
But this will be not the right way to approach this problem.
If you want to hold code in the main class you could do something like this:
public class AClass {
private String a;
public static void main() {
AClass myC = new AClass();
myC.setA("This should be changed");
// than use myC for your further access
}
public String something() {
return a;
}
public String getA() {
return a;
}
public void setA(String a) {
this.a = a;
}
}
If you want to access it by a external class without direct reference you can checkout the singleton pattern.
public class AClass {
private final static AClass INSTANCE = new AClass();
private String a;
public static void main() {
getSingleton().setA("This should be changed");
}
public String something() {
return a;
}
public String getA() {
return a;
}
public void setA(String a) {
this.a = a;
}
public static AClass getSingleton() {
return INSTANCE;
}
}
This way you can access it via AClass.getSingleton() from any location of your code.
You have to call your main() function.
In another class:
itsAClass aClassObj = new itsAClass();
aClassObj.main();
// or rather itsAClass.main() as it is a static function
// now A's value changed
System.out.println(aClassObj.something());
the way to set the value of private variable is by setter and getter methods in class.
example below
public class Test {
private String name;
private String idNum;
private int age;
public int getAge() {
return age;
}
public String getName() {
return name;
}
public String getIdNum() {
return idNum;
}
public void setAge( int newAge) {
age = newAge;
}
public void setName(String newName) {
name = newName;
}
public void setIdNum( String newId) {
idNum = newId;
}
}
you can call method main() in method something().
public class itsAClass{
static private String A;
public static void main() {
A = "This should be changed";
}
public String something() {
main();
return A;
}
public static void main(String[] args){
itsAClass a1 = new itsAClass();
System.out.println(a1.something());// prints This should be changed
}
}

How to use constructor in enum?

I want to use an enum to create a singleton class in java. Should look like this:
public enum mySingleton implements myInterface {
INSTANCE;
private final myObject myString;
private mySingleton(myObject myString) {
this.myString= myString;
}
}
Looks like I cannot use any parameters in the constructor. Is there any workaround for this? Thanks in advance
Yor enum is wrong. Below correct declaration:
public class Hello {
public enum MyEnum {
ONE("One value"), TWO("Two value"); //Here elements of enum.
private String value;
private MyEnum(String value) {
this.value = value;
System.out.println(this.value);
}
public String getValue() {
return value;
}
}
public static void main(String[] args) {
MyEnum e = MyEnum.ONE;
}
}
Output:
One value
Two value
Conctructor is invoked for each element of enum.
You can try this:
enum Car {
lamborghini(900),tata(2),audi(50),fiat(15),honda(12);
private int price;
Car(int p) {
price = p;
}
int getPrice() {
return price;
}
}
public class Main {
public static void main(String args[]){
System.out.println("All car prices:");
for (Car c : Car.values())
System.out.println(c + " costs "
+ c.getPrice() + " thousand dollars.");
}
}
Also see more demos

Selecting correct Enum

I have a number of Enums each of which contain the names of attributes to be tested. The problem I have is how to select the relevant enum for the object. How can I define just a Enum variable which use throughout my code which can be set through an initalise method.
EDIT:
Sorry for the delayed reponse. I had to step away from the desk
It very well be bad design. I have a few enums as follows:
public enum AccountGrpEnum {
Account("Account"),
AccountType("AccountType"),
AcctIDSource("AcctIDSource");
private static Set<String> grpNames = new HashSet<String>(3) {{
for(AccountGrpEnum e : AccountGrpEnum.values()) {
add(e.toString());
}
}};
public static boolean contains(String name) {
return grpNames.contains(name);
}
private String name;
private AccountGrpEnum(String name) {
this.name = name;
}
public String toString() {
return this.name;
}
}
Another Enum:
public enum BlockManValEnum {
avgPx("avgPx"),
quantity("quantity"),
securityIDSource("securityIDSource"),
securityID("securityID"),
blockStatus("blockStatus"),
side("side");
private static Set<String> names = new HashSet<String>(9) {{
for(BlockManValEnum e : BlockManValEnum.values()) {
add(e.toString());
}
}};
public static boolean contains(String name) {
return names.contains(name);
}
private String name;
private BlockManValEnum(String name) {
this.name = name;
}
public String toString() {
return this.name;
}
}
Within my code I am checking the fields of an incoming object to see they are contained within the Enum. As follows:
if (BlockManValEnum.contains(fields[i].getName()))
however I would like it to be along the lines of
if (variableEnum.contains(fields[i].getName()))
Where variableEnum can be set at runtime.
Hope this is clearer guys
Building on previous answers.
enum Color {
RED(1),
GREEN(2),
BLUE(3);
int attrib;
Color(int attribValue) {
attrib = attribValue;
}
public Color getColorForAttrib(int attribValue) {
for(Color c : Color.values()) {
if(c.attrib == attribValue) {
return c;
}
}
throw new IllegalArgumentException("No color could be found for attrib of value " + attribValue);
}
}
...
class SomeClass {
Color c;
public void SomeClass(Color c) {
this.c = c;
}
}
...
class SomeClassUser {
public static void main(String[] args) {
Color c = Color.getColorForAttrib(Integer.valueOf(args[i]));
new SomeClass(c);
}
}
Remember that simplistically, enums are just a class, so you can add any methods you want to them. Whether or not it's a good idea depends on circumstance
Use Enum.valueOf:
Enum<?> variableEnum = AccountGrpEnum.class;
if(Enum.valueOf(variableEnum.getClass(), field[i].getName()) != null) {
doSomething();
}
Since enums are classes and thus can implement interfaces, you could create an interface which holds your contains() method and then implement that method on your enums, then use a generic method which takes a class token of a specific enum type implementing that interface (and which could be set at runtime) to test. Something like this:
CanBeTestedForContains:
public interface CanBeTestedForContains {
boolean contains(String name);
}
ColorEnum:
import java.util.HashSet;
import java.util.Set;
public enum ColorEnum implements CanBeTestedForContains {
R("red"),
B("blue");
private static Set<String> names = new HashSet<String>(3) {
{
for (final ColorEnum e : ColorEnum.values()) {
add(e.name);
}
}
};
private String name;
private ColorEnum(final String name) {
this.name = name;
}
#Override
public boolean contains(final String name) {
return names.contains(name);
}
}
SuitEnum:
import java.util.HashSet;
import java.util.Set;
public enum SuitEnum implements CanBeTestedForContains {
D("diamonds"),
H("hearts"),
C("clubs"),
S("spades");
private static Set<String> names = new HashSet<String>(3) {
{
for (final SuitEnum e : SuitEnum.values()) {
add(e.name);
}
}
};
private String name;
private SuitEnum(final String name) {
this.name = name;
}
#Override
public boolean contains(final String name) {
return names.contains(name);
}
}
ContainsSelectorTest:
public class ContainsSelectorTest {
private static <E extends Enum<E> & CanBeTestedForContains> boolean contains(final Class<E> enumClass, final String name) {
return enumClass.getEnumConstants()[0].contains(name);
}
public static void main(final String[] args) {
if (contains(ColorEnum.class, "red")) {
System.out.printf("%s contains %s\n", ColorEnum.class, "red");
}
if (contains(SuitEnum.class, "hearts")) {
System.out.printf("%s contains %s\n", SuitEnum.class, "hearts");
}
if (contains(SuitEnum.class, "red")) {
System.out.println("This shouldn't happen.");
} else {
System.out.printf("%s DOES NOT contain %s\n", SuitEnum.class, "red");
}
}
}
Output:
class ColorEnum contains red
class SuitEnum contains hearts class
class SuitEnum DOES NOT contain red

Json Jackson deserialization without inner classes

I have a question concerning Json deserialization using Jackson.
I would like to deserialize a Json file using a class like this one:
(taken from http://wiki.fasterxml.com/JacksonInFiveMinutes)
public class User
{
public enum Gender { MALE, FEMALE };
public static class Name {
private String _first, _last;
public String getFirst() { return _first; }
public String getLast() { return _last; }
public void setFirst(String s) { _first = s; }
public void setLast(String s) { _last = s; }
}
private Gender _gender;
private Name _name;
private boolean _isVerified;
private byte[] _userImage;
public Name getName() { return _name; }
public boolean isVerified() { return _isVerified; }
public Gender getGender() { return _gender; }
public byte[] getUserImage() { return _userImage; }
public void setName(Name n) { _name = n; }
public void setVerified(boolean b) { _isVerified = b; }
public void setGender(Gender g) { _gender = g; }
public void setUserImage(byte[] b) { _userImage = b; }
}
A Json file can be deserialized using the so called "Full Data Binding" in this way:
ObjectMapper mapper = new ObjectMapper();
User user = mapper.readValue(new File("user.json"), User.class);
My problem is the usage of the inner class "Name". I would like to do the same thing without using inner classes. The "User" class would became like that:
import Name;
import Gender;
public class User
{
private Gender _gender;
private Name _name;
private boolean _isVerified;
private byte[] _userImage;
public Name getName() { return _name; }
public boolean isVerified() { return _isVerified; }
public Gender getGender() { return _gender; }
public byte[] getUserImage() { return _userImage; }
public void setName(Name n) { _name = n; }
public void setVerified(boolean b) { _isVerified = b; }
public void setGender(Gender g) { _gender = g; }
public void setUserImage(byte[] b) { _userImage = b; }
}
This means to find a way to specify to the mapper all the required classes in order to perform the deserialization.
Is this possible? I looked at the documentation but I cannot find any solution.
My need comes from the fact that I use the Javassist library to create such classes, and it does not support inner or anonymous classes.
Thank you in advance
There should be no difference between the static inner class Name, and the top-level class of the same name. The Jackson runtime should not be able to meaningfully distinguish between the two situations.
Have you tried moving the Name class out of User, changing it into a top-level class? It should still work as before.
edit: I just tried this, and it works fine when Name is a top-level class. The example had it as an inner class for the sake of brevity, I suspect.
mr. Skaffman's answer is right on. The only additional thing to mention is that unlike JAXB, Jackson does not generally require you to specify classes you operate on, except for the root class (and not always even that, if you use Polymorphic Handling).

Categories

Resources