Suppose I have a Enum defined something like this:
public enum Sample{
// suppose AClass.getValue() returns an int
A(AClass.getValue()),
B(AClass.getValue()),
C(AClass.getValue());
private int _value;
private Sample(int _val){
this._value = _val;
}
public int getVal(){
return _value;
}
I can pull out values using Sample.A or Sample.A.getAVal() without issue.
Now suppose that AClass.getValue() could take a parameter to return a possibly different particular value, eg AClass.getValue(42).
It is possible to pass arguments to a public Enum method and retrive the Enum values? In other words, could I have an Enum definition like
public enum Sample{
// suppose AClass.getValue() returns an int
A(AClass.getAValue()),
B(AClass.getBValue()),
C(AClass.getCValue());
private int _value;
private Sample(int _val){
this._value = _val;
}
public int getVal(){
return _value;
}
public int getVal(int a){
// somehow pull out AClass.getAValue(a)
}
using Sample.A.getValue(42)?
You can do it, but only by making an abstract method in the enum, and overriding it in each value:
public enum Sample {
A(AClass.getAValue()) {
#Override public int getVal(int x) {
return AClass.getAValue(x);
}
},
B(BClass.getAValue()) {
#Override public int getVal(int x) {
return BClass.getBValue(x);
}
},
C(CClass.getAValue()) {
#Override public int getVal(int x) {
return CClass.getCValue(x);
}
};
private int _value;
private Sample(int _val){
this._value = _val;
}
public int getVal(){
return _value;
}
public abstract int getVal(int x);
}
Of course if you could create an instance of some other base type which has a getValue(int x) method, then you could put the code into the enum class itself instead of into the nested ones.
As stated in Java Specification
there is only one instance of each enum constant
So no, you can't have different values of a specific enum constant.
But you could put an array or a map inside your enum, so Sample.A.getValue(42) would return Sample.A.myMap.get(42) :
public enum Sample{
A(),
B(),
C();
Map<Integer, Integer> myMap = new HashMap<Integer, Integer>();
public int getVal(int i){
return myMap.get(i);
}
public int setVal(int i, int v){
return myMap.put(i, v);
}
}
public class App {
public static void main(String[] args) {
Fruit.setCounter(5);
System.out.println(Fruit.Apple.getCmd());
Fruit.setCounter(6);
System.out.println(Fruit.Apple.getCmd());
}
}
public enum Fruit {
Apple {
public String getCmd() {
return counter + " apples";
}
},
Banana {
public String getCmd() {
return counter + " bananas";
}
};
private static int counter = 0;
public abstract String getCmd();
public static void setCounter(int c) {
counter = c;
}
}
Output:
5 apples
6 apples
Related
My requirement is I want to pass the Enum as the parameter in the function,and from the function want to print the value of Enum. For Example Enum, Category.ONE should print 1. Similarly for TWO should print 2 and for THREE should print 3.
I assigned the value Enum, like 1, 2, 3.
enum Category {
ONE(1),
TWO (2),
THREE(3);
private final Integer num;
Category(Integer val) {
num = val;
}
}
public class EnumDemo1 {
public static void printEnumValue(Category category){
System.out.println(category.name()); // Want to print the value of ENUM. 1, 2, 3
}
public static void main(String[] args) throws Exception {
for(Category category: Category.values()){
printEnumValue(category);
}
}
}
You can add a method that returns num, e.g.:
enum Category {
ONE(1),
TWO (2),
THREE(3);
private final Integer num;
Category(Integer val) {
num = val;
}
public int getValue() {
return num;
}
}
And then, call it from printEnumValue, e.g.:
public static void printEnumValue(Category category){
System.out.println(category.getValue()); // Want to print the value of ENUM. 1, 2, 3
}
Declare a getter for the field, or make it public:
enum Category {
ONE(1),
TWO (2),
THREE(3);
private final Integer num;
Category(Integer val) {
num = val;
}
public int getNum() {
return num;
}
}
public class EnumDemo1 {
public static void printEnumValue(Category category){
System.out.println(category.getNum()); // Want to print the value of ENUM. 1, 2, 3
}
public static void main(String[] args) throws Exception {
for(Category category: Category.values()){
printEnumValue(category);
}
}
}
Also, enums have ordinals, which return an integer, describing the order of the enum value.
remove final modifier for num field and declare getter method
enum Category {
ONE(1),
TWO (2),
THREE(3);
//
private Integer num;
Category(Integer val) {
this.num = val;
}
public int getValue() {
return num;
}
}
public class EnumDemo1 {
public static void printEnumValue(Category category){
System.out.println(category.getValue()); // Want to print the value of ENUM. 1, 2, 3
}
public static void main(String[] args) throws Exception {
for(Category category: Category.values()){
printEnumValue(category);
}
}
}
see https://docs.oracle.com/javase/tutorial/java/javaOO/enum.html for more
i started learning a bit more about Java and got stuck here :
Wanted to make Objects that contain value, index and a rest and in main method a list of objects.
By adding new objects to the list the previous entry gets overwritten.
Here is my code so far :
public class LNGHW {
public static int value;
public static int index;
public static int rest;
public LNGHW(int val, int index, int mod) {
this.value = val;
this.index = index;
this.rest = mod;
}
public static void main(String[] args) {
ArrayList<LNGHW> items = new ArrayList<LNGHW>();
items.add(new LNGHW(4, 0, 1));
items.add(new LNGHW(2, 1, 1));
System.out.println(items.get(0).getValue());
System.out.println(items.get(1).getValue());
}
public int getValue() {
return value;
}
public static void setValue(int value) {
LNGHW.value = value;
}
public static int getIndex() {
return index;
}
public static void setIndex(int index) {
LNGHW.index = index;
}
public static int getRest() {
return rest;
}
public static void setRest(int rest) {
LNGHW.rest = rest;
}
}
I am open for every kind of help!
import java.util.*;
import java.lang.*;
import java.io.*;
class LNGHW {
public int value; /*made them non-static*/
public int index;
public int rest;
public LNGHW(int val, int index, int mod) {
this.value = val;
this.index = index;
this.rest = mod;
}
public static void main(String[] args) {
ArrayList<LNGHW> items = new ArrayList<LNGHW>();
items.add(new LNGHW(4, 0, 1));
items.add(new LNGHW(2, 1, 1));
System.out.println(items.get(0).getValue());
System.out.println(items.get(1).getValue());
}
public int getValue() {
return this.value;
}
public void setValue(int value) { /*made these values non-static*/
this.value = value; /*set the values of object using **this**,not class name */
}
public int getIndex() {
return this.index;
}
public void setIndex(int index) {
this.index = index;
}
public int getRest() {
return this.rest;
}
public void setRest(int rest) {
this.rest = rest;
}}
To understand why it was happening you need to understand about static,non-static and this keyword in java. Please study about them and then you can understand the difference.
STATIC--when we want any property to be same for every object of a class then we use static keyword. For eg- suppose there is a MAN class and there are few attributes such as age,gender etc, then age will be different for different objects of man class i.e. age attribute is a object level property hence it will be non-static. whereas gender of every object of the MAN class will be male,hence it is a class level property and therefore it should be static.
Finally whenever there is a class level property we use static variables otherwise for object level property we use non-static variables.
we use this keyword to refer non-static variables where as class name for referring static variables.
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
I want to have a list of constants like A, B, C related to integers 1, 2, 3
I know you can do like
class Example {
public static final int A = 1;
etc...
}
and
enum Example {
A(1), ... etc;
some initialization of an integer
}
But is there a way to do it like the public static final but as succinct as enums? When I use A and I really mean 1 I don't want to call Example.A.value or something like that.
One way would be to use an interface, where variables are public, static and final by default:
interface Example {
int A = 1;
int B = 2;
}
If I understand what you're asking correctly, you want to do something like this:
enum Example {
A = 1,
B = 2,
....
}
There is no nice simple syntax for this.
You either have to write out some constants:
public interface Example {
public static final int A = 1;
public static final int B = 2;
....
}
...Or you can add some other value to the enum:
public enum Example {
A(1),
B(2)
....
private final int val;
public Example (int val) {
this.val = val;
}
public int getValue() {
return val;
}
}
I think the shortest solution is:
public static final int A = 1, B = 2, C = 3;
If you really want to use Enum, then you can override toString() method in your enum, to get the value printed when you print your Enum Instance: -
enum Example {
A(1), B(2);
private int val;
private Example(int val) {
this.val = val;
}
#Override
public String toString() {
switch (this) {
case A:
return String.valueOf(val);
case B:
return String.valueOf(val);
}
return super.toString();
}
}
public class D {
public static void main(String[] args) {
Example a = Example.A;
Example b = Example.B;
System.out.println(a); // Prints 1
System.out.println(b); // Prints 2
}
}
Ideally your above enum is just like the below class: -
class Example {
public static final int A = 1;
public static final int B = 2;
}
So, I don't see the necessity of using Enums..
I use the enum to make a few constants:
enum ids {OPEN, CLOSE};
the OPEN value is zero, but I want it as 100. Is it possible?
Java enums are not like C or C++ enums, which are really just labels for integers.
Java enums are implemented more like classes - and they can even have multiple attributes.
public enum Ids {
OPEN(100), CLOSE(200);
private final int id;
Ids(int id) { this.id = id; }
public int getValue() { return id; }
}
The big difference is that they are type-safe which means you don't have to worry about assigning a COLOR enum to a SIZE variable.
See http://docs.oracle.com/javase/tutorial/java/javaOO/enum.html for more.
Yes. You can pass the numerical values to the constructor for the enum, like so:
enum Ids {
OPEN(100),
CLOSE(200);
private int value;
private Ids(int value) {
this.value = value;
}
public int getValue() {
return value;
}
}
See the Sun Java Language Guide for more information.
whats about using this way:
public enum HL_COLORS{
YELLOW,
ORANGE;
public int getColorValue() {
switch (this) {
case YELLOW:
return 0xffffff00;
case ORANGE:
return 0xffffa500;
default://YELLOW
return 0xffffff00;
}
}
}
there is only one method ..
you can use static method and pass the Enum as parameter
like:
public enum HL_COLORS{
YELLOW,
ORANGE;
public static int getColorValue(HL_COLORS hl) {
switch (hl) {
case YELLOW:
return 0xffffff00;
case ORANGE:
return 0xffffa500;
default://YELLOW
return 0xffffff00;
}
}
Note that these two ways use less memory and more process units .. I don't say this is the best way but its just another approach.
If you use very big enum types then, following can be useful;
public enum deneme {
UPDATE, UPDATE_FAILED;
private static Map<Integer, deneme> ss = new TreeMap<Integer,deneme>();
private static final int START_VALUE = 100;
private int value;
static {
for(int i=0;i<values().length;i++)
{
values()[i].value = START_VALUE + i;
ss.put(values()[i].value, values()[i]);
}
}
public static deneme fromInt(int i) {
return ss.get(i);
}
public int value() {
return value;
}
}
If you want emulate enum of C/C++ (base num and nexts incrementals):
enum ids {
OPEN, CLOSE;
//
private static final int BASE_ORDINAL = 100;
public int getCode() {
return ordinal() + BASE_ORDINAL;
}
};
public class TestEnum {
public static void main (String... args){
for (ids i : new ids[] { ids.OPEN, ids.CLOSE }) {
System.out.println(i.toString() + " " +
i.ordinal() + " " +
i.getCode());
}
}
}
OPEN 0 100
CLOSE 1 101
The ordinal() function returns the relative position of the identifier in the enum. You can use this to obtain automatic indexing with an offset, as with a C-style enum.
Example:
public class TestEnum {
enum ids {
OPEN,
CLOSE,
OTHER;
public final int value = 100 + ordinal();
};
public static void main(String arg[]) {
System.out.println("OPEN: " + ids.OPEN.value);
System.out.println("CLOSE: " + ids.CLOSE.value);
System.out.println("OTHER: " + ids.OTHER.value);
}
};
Gives the output:
OPEN: 100
CLOSE: 101
OTHER: 102
Edit: just realized this is very similar to ggrandes' answer, but I will leave it here because it is very clean and about as close as you can get to a C style enum.
#scottf
An enum is like a Singleton. The JVM creates the instance.
If you would create it by yourself with classes it could be look like that
public static class MyEnum {
final public static MyEnum ONE;
final public static MyEnum TWO;
static {
ONE = new MyEnum("1");
TWO = new MyEnum("2");
}
final String enumValue;
private MyEnum(String value){
enumValue = value;
}
#Override
public String toString(){
return enumValue;
}
}
And could be used like that:
public class HelloWorld{
public static class MyEnum {
final public static MyEnum ONE;
final public static MyEnum TWO;
static {
ONE = new MyEnum("1");
TWO = new MyEnum("2");
}
final String enumValue;
private MyEnum(String value){
enumValue = value;
}
#Override
public String toString(){
return enumValue;
}
}
public static void main(String []args){
System.out.println(MyEnum.ONE);
System.out.println(MyEnum.TWO);
System.out.println(MyEnum.ONE == MyEnum.ONE);
System.out.println("Hello World");
}
}
public class MyClass {
public static void main(String args[]) {
Ids id1 = Ids.OPEN;
System.out.println(id1.getValue());
}
}
enum Ids {
OPEN(100), CLOSE(200);
private final int id;
Ids(int id) { this.id = id; }
public int getValue() { return id; }
}
#scottf, You probably confused because of the constructor defined in the ENUM.
Let me explain that.
When class loader loads enum class, then enum constructor also called. On what!! Yes, It's called on OPEN and close. With what values 100 for OPEN and 200 for close
Can I have different value?
Yes,
public class MyClass {
public static void main(String args[]) {
Ids id1 = Ids.OPEN;
id1.setValue(2);
System.out.println(id1.getValue());
}
}
enum Ids {
OPEN(100), CLOSE(200);
private int id;
Ids(int id) { this.id = id; }
public int getValue() { return id; }
public void setValue(int value) { id = value; }
}
But, It's bad practice. enum is used for representing constants like days of week, colors in rainbow i.e such small group of predefined constants.
I think you're confused from looking at C++ enumerators. Java enumerators are different.
This would be the code if you are used to C/C++ enums:
public class TestEnum {
enum ids {
OPEN,
CLOSE,
OTHER;
public final int value = 100 + ordinal();
};
public static void main(String arg[]) {
System.out.println("OPEN: " + ids.OPEN.value);
System.out.println("CLOSE: " + ids.CLOSE.value);
System.out.println("OTHER: " + ids.OTHER.value);
}
};