Enum type conversion to int - java

i am trying to use the following code...
The Enum class i am using is
public enum AccountType {
kAccountTypeAsset(0x1000),
kAccountTypeAssetFixed(0x1010),
private int value;
private AccountType(int value)
{
this.value = value;
}
public int getValue()
{
return value;
}
}
public AccountType accountType = kAccountTypeAsset;
integerToDB(accountType);
...
/*************************/
public Object integerToDB (Integer i )
{
if(i == -1)
{
return null;
}
return i;
}
How can i use
accountType
as integer.

integerToDB(accountType.getValue()); ?

Since your enum has implemented a getValue method, you can use accountType.getValue() to get the integer value stored in accountType.

Related

Deserializing json response to custom enum value in java

I am trying to deserialize a JSON response with custom enum values, but instead of mapping with the custom value, the enum is being set with its ordinal value. I have searched a lot and I can not figure out what I am doing wrong. Any help would be great.
The response is
{"id":12, "status":1}
Corresponding enum object and enum is
public class Car {
int id;
CarStatus status;
}
public enum CarStatus {
READY(1),
WAITING(2);
private int value;
CarStatus(int value) {
this.value = value;
}
#JsonValue
public int getValue() {
return value;
}
}
The status is set to WAITING, but I expect it to be set to READY.
your enum miss #JsonCreator
try like this:
public enum CarStatus {
READY(1),
WAITING(2);
private int value;
CarStatus(int value) {
this.value = value;
}
#JsonValue
public int getValue() {
return value;
}
#JsonCreator
public static CarStatus getItem(int code){
for(CarStatus item : values()){
if(item.getValue() == code){
return item;
}
}
return null;
}
}
you can see my code in github: https://github.com/onemaomao/java-common-mistakes/tree/master/src/main/java/org/geekbang/time/questions/stackoverflow/reslove/q1
This seems so be a known problem for enums when using an integer in combination with only a #JsonValue annotation. There are open issues on Github which refer to this (e.g. 1 and 2) which are currently planned for version 2.13.
In the meantime, you can solve this by adding a #JsonCreator which returns the corresponding CarStatus:
public enum CarStatus {
READY(1),
WAITING(2);
private final int value;
CarStatus(int value) {
this.value = value;
}
#JsonValue
public int getValue() {
return this.value;
}
#JsonCreator
public static CarStatus getByValue(int value) {
for (CarStatus status : values()) {
if (status.value == value) {
return status;
}
}
return null;
}
}
Code to test:
ObjectMapper objectMapper = new ObjectMapper();
Car original = new Car();
original.setId(45);
original.setStatus(CarStatus.READY);
String json = objectMapper.writeValueAsString(original);
Car reconstruction = objectMapper.readValue(json, Car.class);
System.out.println(json);
System.out.println(reconstruction.getStatus());
Output:
{"id":45,"status":1}
READY

Create an empty constructor when wrong parameters

class classname {
private int value;
public classname(int value) {
if(value > 20 || value < 1) {
//make object null
}
else {
this.value = value;
}
}
}
Basically, when the parameter is not in the range I want to make an empty object.
something like:
classname newclass = new classname(100);
if(newclass == null) {
//this is what i want
}
Instead of initialising an object with null, you should throw an IllegalArgumentException, e.g.:
if(value > 20 || value < 1) {
throw new IllegalArgumentException("Value must be between 1 and 20");
}
This would prevent the initialisation and return correct error message to the user. Also, this is considered as best practice (e.g. try calling Integer.parseInt("abc");)
For this look at factory design. You should create a factory class and let that factory return the class instance. Inside factory implementation you can write the logic based on parameter.
Look at this post.
Create Instance of different Object Based on parameter passed to function using C#
You should create a factory method which either return instance if argument is valid or null and hide the constructor using private:
class YourClass {
private int value;
// Factory method
public static YourClass newYourClass(int value) {
if(value > 20 || value < 1)
return null;
else
return new YourClass(value);
}
private YourClass(int value) {
this.value = value;
}
}
You can make it in this way
public class MyClass {
private int value; // if -1 not in the range!
public MyClass(int value) {
if (value > 20 || value < 1) {
this.value = -1;
} else {
this.value = value;
}
} //end of constructor
} //end of the MyClass
you can do somthing like this
class classname {
private Integer value;
public classname(Integer value) {
this.value = value <1 || value>20 ? null : value;
}
}
public class CustomObjectFactory
{
private int value;
CustomObjectFactory(int value)
{
this.value = value;
}
public CustomObjectFactory getInstance()
{
System.out.print(value);
if(value<10)
{
System.out.print("if"+value);
return null;
}else
{
System.out.print("else"+value);
return new CustomObjectFactory(value);
}
}
}

Getting enum value by passing preset ordinal

I have looked this link : Convert from enum ordinal to enum type
and tried to get the enum value. But is not working. My enum class is :
public enum OrderStatus {
OPEN(0),
DELIVERED(1),
CANCELLED(3),
PARTIALLY(4)
}
I will pass the values 0,1,3,4 where 2 is missing , so it has no such order. How to get enum by passing 0,1,3 or 4 in groovy or java.
Add a field to the enum, and a constructor:
public enum OrderStatus {
private Integer codice;
public Integer getCodice() {
return codice;
}
private OrderStatus(Integer codice) {
this.codice = codice;
}
OPEN(0),
DELIVERED(1),
CANCELLED(3),
PARTIALLY(4)
}
and then you can define a method like this:
public static OrderStatus getByCodice(int codice) {
for (OrderStatus tipo : values()) {
if (tipo.codice == codice) {
return tipo;
}
}
throw new IllegalArgumentException("Invalid codice: " + codice);
}
Record the value in the enum and build a Map to convert.
public enum OrderStatus {
OPEN(0),
DELIVERED(1),
CANCELLED(3),
PARTIALLY(4);
final int ordinal;
private OrderStatus(int ordinal) {
this.ordinal = ordinal;
}
static Map<Integer, OrderStatus> lookup = null;
public static OrderStatus lookup(int ordinal) {
// Could just run through the array of values but I will us a Map.
if (lookup == null) {
// Late construction - not thread-safe.
lookup = Arrays.stream(OrderStatus.values())
.collect(Collectors.toMap(s -> s.ordinal, s -> s));
}
return lookup.get(ordinal);
}
}
public void test() {
for (int i = 0; i < 5; i++) {
System.out.println(i + " -> " + OrderStatus.lookup(i));
}
}
Just declare a field inside enum as you do in class. And provide a getter method for the field:
public enum OrderStatus
{
OPEN(0),
DELIVERED(1), /*pass value*/
CANCELLED(3),
PARTIALLY(4);
private int value; /*Add a field*/
OrderStatus ( int value )
{
this.value = value;
}
/*Access with getter*/
int getValue ( )
{
return value;
}
}

can not define int variable in enum - java

i try to define enum with int in it, but i have error in eclipse : "Syntax error on token "int", delete this token"
my code:
package util.enumurations;
public enum BooleanEnum
{
private int value;
static
{
BooleanEnum[] arrayOfBooleanEnum = new BooleanEnum[2];
arrayOfBooleanEnum[0] = False;
arrayOfBooleanEnum[1] = True;
}
private BooleanEnum(int arg3)
{
int j;
this.value = j;
}
public int getValue()
{
return this.value;
}
}
The first thing in an enum have to be the declaration of the possible values.
public enum BooleanEnum
{
False(0), True(1);
private final int value;
static
{
BooleanEnum[] arrayOfBooleanEnum = new BooleanEnum[2];
arrayOfBooleanEnum[0] = False;
arrayOfBooleanEnum[1] = True;
}
private BooleanEnum(int arg3)
{
this.value = arg3;
}
public int getValue()
{
return this.value;
}
}
Use
java.lang.Boolean.TRUE,
java.lang.Boolean.FALSE
instead
Actually The body of an enum type may contain enum constants. An enum constant defines an instance of the enum type.
What you are trying to is You aren't gonna need it.
Just use a simple Boolean almost it self acts as ENUM for true false types.
Use Boolean.valueOf();

sort custom Array List

I have a class called x which is a array list and needs to be sorted in Decreasing order by Value.
My Class-
public static class x
{
public int id;
public double value;
public x(int _id, double _value)
{
id = _id;
value = _value;
//System.out.println(Integer.toString(id));
}
public Integer getID(){
return id;
}
public double getValue(){
return value;
}
//Sorting
public static Comparator<x> getComparator(SortParameter... sortParameters) {
return new xComparator(sortParameters);
}
public enum SortParameter {
VAL_DESCENDING
}
private static class xComparator implements Comparator<x> {
private SortParameter[] parameters;
private xComparator(SortParameter[] parameters) {
this.parameters = parameters;
}
public int compare(x o1, x o2) {
int comparison;
for (SortParameter parameter : parameters) {
switch (parameter) {
case VAL_DESCENDING:
comparison = o2.id - o1.id;
if (comparison != 0) return comparison;
break;
}
}
return 0;
}
}
}
I Call it like:
cp = x.getComparator(x.SortParameter.VAL_DESCENDING);
Collections.sort(attr1, cp);
attr1 is my array list
Just for Reference I am following this
I am getting error:
cannot find symbol : variable cp
I am a newbie to java :(
try using Comparator<x> cp = x.getComparator(x.SortParameter.VAL_DESCENDING); to declare it. you can not use a variable until it is declared

Categories

Resources