Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

passing enums by ref in java

How can i pass enum parameter by reference in java? Any solution?

like image 446
aam Avatar asked Oct 22 '10 13:10

aam


People also ask

Can you use == for enums?

Because there is only one instance of each enum constant, it is permissible to use the == operator in place of the equals method when comparing two object references if it is known that at least one of them refers to an enum constant.

How do you pass an enum as an argument?

enums are technically descendants of Enum class. So, if you want to use only Enum's standard methods in your method (such as values()), pass the parameter like this: static void printEnumValue(Enum generalInformation) See, that the only thing you have to change is the capital letter E.

Can we inherit enums?

Inheritance Is Not Allowed for Enums.

Can you give enums values?

By default enums have their own string values, we can also assign some custom values to enums.


2 Answers

In Java you cannot pass any parameters by reference.

The only workaround I can think of would be to create a wrapper class, and wrap an enum.

public class EnumReference {
    public YourEnumType ref;
}

And then you would use it like so:

public void someMethod(EnumReference reference) {
    reference.ref = YourEnumType.Something;
}

Now, reference will contain a different value for your enum; essentially mimicking pass-by-reference.

like image 88
jjnguy Avatar answered Oct 14 '22 12:10

jjnguy


Java is pass by value - always.

You pass references, not objects. References are passed by value.

You can change the state of a mutable object that the reference points to in a function that it is passed into, but you cannot change the reference itself.

like image 39
duffymo Avatar answered Oct 14 '22 12:10

duffymo