I need a mutable boolean field in Java (I will return this field via get* method later and it should be possible to modify this field).
Boolean doesn't work because there are no set* methods in the Boolean class (I would say that Boolean is immutable, you can only change the reference, but you can't change the object itself).
I guess I can use Boolean array of size 1. But probably there are more elegant solutions?
Why doesn't Java have such a simple thing?
Immutable classes are easier to work with. They'll never change and there will be no problems with concurrent code. (Basically, there are fewer possibilities to break them.)
If you would like to return a reference to your Boolean value, you can use java.util.concurrent.atomic.AtomicBoolean if you're working with multiple threads or plain old org.apache.commons.lang.mutable.MutableBoolean.
Maybe write yourself a wrapper class
class BooleanHolder {
public boolean value;
}
Or make a generic holder class (which means you will have to use class Boolean instead of primitive boolean):
class Holder<T> {
public T value;
}
You then return the wrapper class instead of the value itself, which allows the value inside the wrapper to be modified.
If you are using Java 5 or higher then use AtomicBoolean
You can use a boolean array
final boolean[] values = { false };
values[0] = true;
What about just using the boolean primitive?
private boolean value;
public void setValue(boolean value) {
this.value = value;
}
public boolean getValue() {
return value;
}
Why not use the boolean primitive ?
e.g.
private boolean myFlag = false;
public void setMyFlag(boolean flag) {
myFlag = flag;
}
Note your getter method can return a Boolean if required, due to the magic of autoboxing. This allows easy interchangeability between using primitives and their object equivalents (e.g. boolean vs. Boolean, or int vs. Integer).
So to address your edited responses re. the methods you have available,
public Object getAttribute(String attributeName)
can be implemented by returning an autoboxed boolean,.
The answer I liked most was from Adam to write your own wrapper class... OK
/* Boolean to be passed as reference parameter */
public class Bool {
private boolean value;
public Bool() {
this.value = false;
}
public boolean is() {
return this.value;
}
public void setTrue() {
this.value = true;
}
public void setFalse() {
this.value = false;
}
}
If you are using Android, you can use the android.util.Mutable* objects which wrap various primitive values. For example, quoting from the SDK source:
public final class MutableBoolean {
public boolean value;
public MutableBoolean(boolean value) {
this.value = value;
}
}
Are you really saying that you want callers to be able to modify the object's boolean value by manipulating what gets returned? So that the object and caller would share a reference to it?
Just so I understand, given:
class OddClass {
private Boolean strangeFlag;
public Object getAttrbiute(String attributeName) {
if (attributeName.equals("strangeflag")) return (Object)strangeFlag;
...
}
}
And then caller does:
Boolean manipulableFlag = (Boolean) myOddClass.getAttrbiute ("strangeflag");
And then later, if caller changes the value of manipulableFlag, you want that change to happen in the OddClass instance, just as though caller had instead used a setAttrbiute method.
Is that what you're asking?
In that case, you'd need a holder class, as suggested by Adam.
Related
I have a question regarding to the andriod #IntDef Annotation. I know
that in its basic usage, it should replace the enum. But what if
I have a parameterized enum with multiple hardwired values for example
public enum MyEnum {
YES(true, 1),
NO(false, 0);
private boolean boolState;
private boolean intState;
MyEnum(boolean boolState, int intState) {
this.boolState = boolState;
this.intState = intState;
}
public boolean getBoolState() {
return boolState;
}
public int getIntState() {
return intState;
}
}
How would this be replaced by an Enumerated Annotation in Android?
Is it even suggestive to do something like that in this case? I searched
everywhere, but I haven't found any answer for that.
Thank you in advance!
I don't think you would be able to find anything because:
IntDef is a way of replacing an integer enum where there's a parameter
that should only accept explicit int values.
you can read more about it here. Enumerated annotations are for simple types, you could use it for strings also StringDef. Use enum when you need its features. Don't avoid it strictly. For your case I think creating class instead of enum would look like this:
public class MyEnum {
public static final MyEnum YES = new MyEnum(true, 1);
public static final MyEnum NO = new MyEnum(false, 0);
private boolean boolState;
private int intState;
MyEnum(boolean boolState, int intState) {
this.boolState = boolState;
this.intState = intState;
}
public boolean getBoolState() {
return boolState;
}
public int getIntState() {
return intState;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
MyEnum myEnum = (MyEnum) o;
return boolState == myEnum.boolState && intState == myEnum.intState;
}
}
and you could use constants in your code. But if using enums you will have type checking (you'll be able to accept only listed values) and method overloading (every enum constant can have its own implementation of a method). If you want to use less space and that is the only reason why you want to avoid using enum I would suggest you that it's not worth it.
I follow a rule with enums in Android development:
if it has no params, use an intdef/stringdef,
if it has params, use an enum
If there is a way around using an enum, I'll certainly consider it where it doesn't undermine the code.
A lot was made from the video Colt Mcanlis posted: https://www.youtube.com/watch?v=Hzs6OBcvNQE&feature=youtu.be
however it had some fairly shaky numbers in it as pointed out by Jake Wharton: https://plus.google.com/+JakeWharton/posts/bTtjuFia5wm
The main drawback of enums is that they use more memory than constants would, but if that enum aids in better code, I say use it rather than micro-optimise. Just don't go overboard using them and be aware of their footprint.
I'm coming late, but anyways, since intdef ins an annotation, you can create an annotation using a custom class and then use it in the same way. given the fact an annotation needs primitives, you'll have to pass an interface as the annotation class type, and use subclasses as the value array.
example:
public interface GenericContainer<T, X> {
public T getValueOne();
public X getValueTwo();
}
then an implementation for true/1
public class TrueContainer implements GenericContainer<Boolean, Integer> {
#Override
public Boolean getValueOne() {
return true;
}
#Override
public Integer getValueTwo() {
return 1;
}
}
and other for false/0
public class FalseContainer implements GenericContainer<Boolean, Integer> {
#Override
public Boolean getValueOne() {
return false;
}
#Override
public Integer getValueTwo() {
return 0;
}
}
finally, use them:
#Retention(RetentionPolicy.SOURCE)
#GenericDef({TrueContainer.class, FalseContainer.class})
public #interface genericTest{}
boolean test = isTest(new FalseContainer());
I have Enumeration classes in my application and I am using this enumerations to compare value of BigIntegers like this:
if (user.getObjId.equals(RoleEnum.ADMIN.getValue())) {
//something happens
}
The question is, can I modify this enumeration class to use it without calling getValue() method, as shown in following code sample?
if (user.getObjId.equals(RoleEnum.ADMIN)) {
//something happens
}
Here is my Enumeration class:
public enum RoleEnum {
ADMIN(1), USER(2);
private final BigInteger value;
private RoleEnum(int value) {
this.value = BigInteger.valueOf(value);
}
public BigInteger getValue() {
return value;
}
}
the idea behind BigInteger is that you can work with numbers that are so big you can just type in a numeric way on the IDE...
you should do:
ADMIN("1"), USER("2");
private RoleEnum(String value) {
this.value = BigInteger.valueOf(value);
The answer to your question is simply 'No'.
It all depends on the equals method of the objectId. You can not override the equals method of the enum, but you could possibly override/declare the equals method on the objectId (it's hard to say from the information you provided).
The implementation of the equals method can then check for the type of the parameter to be of the enum type, and in that case, compare the values. For example:
public boolean equals(Object o){
if(o instanceof RoleEnum){
return this.value.equals(((RoleEnum)o).getValue());
}
...
}
But I assume, your objId is of type BigInteger, so you cant override the equals method. In that case, the answer is as mention above: 'No'
If something's not very neat refactor out a method so it looks neat again (especially if it happens in more than one place):
if (user.isRole(RoleEnum.ADMIN))
on User (I'm assuming the name of the type of user):
public boolean isRole(RoleEnum role) {
return getObjId.equals(role.getValue());
}
Or if it's not not possible to modify User or reference the enum from there, then maybe a static:
public final class UserHelpers {
private UserHelpers(){}
public static boolean userIsRole(User user, RoleEnum role) {
return user.getObjId.equals(role.getValue());
}
}
Usage:
if (UserHelpers.userIsRole(user, RoleEnum.ADMIN))
Or with the static imported:
if (userIsRole(user, RoleEnum.ADMIN))
I know this is fairly simple topic, but I really want to wrap my head around it.
This is what I'm trying to do, but it doesn't like the final modifier. Is there another way to achieve the effect I'm looking for? Which is basically that I want to make sure the id can not change durning the Activities entire life.
private final long mId;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mId = getIntent().getLongExtra(ID_KEY, -1);
}
I should point out that this is Android code. Thanks for all the help. I'm not worried about getters or setters or anyone changing my code. The reason I asked was to future proof my code for the next developer to take over. I found this post that also helps shed some light. Android - Activity Constructor vs onCreate
You can set a final variable only in a constructor or in an initializer. Regular methods cannot change the value of variables declared final.
You can't. But you can guarantee no external object changes it if it's private and you don't have a setter for it.
Alternatively, you can wrap the long value in another class - LazyImmutableLong. But this is a more verbose approach, and you probably don't need it (note: the class below is not thread-safe)
class LazyImmutableLong {
private Long value;
public void setValue(long value) {
if (this.value != null) {
return; // the value has already been set
}
this.value = value;
}
public long getValue() {return value;}
}
And in your activity
private LazyImmutableLong id = new LazyImmutableLong();
public void onCreate(..) {
id.setValue(..);
}
The following Worm (Write-Once-Read-Many) class could help in this kind of scenario.
We could create a nested Wrapper class, that stores the final variable you need. To initialize this variable, you just should call a constructor of the wrapper object. When you call the method getData(), you will get a reference of the final variable in case it is initialized, otherwise, you will get null.
The methods getData() and setData(T data) are required to be thread-safe. To provide it, we use a volatile modifier for the wrapper object. Reading a volatile variable is synchronized and writing to a volatile variable is synchronized, too. Even though some efforts were made to make this code thread-safe I didn't test it in this respect. Depending on the level of thread safety you may consider to make setter and getter synchronized.
public class Worm<T> {
private volatile Wrapper<T> wrapper;
public Worm() {}
public Worm(T data) throws IllegalAccessError
{
setData(data);
}
public T getData()
{
if (wrapper == null)
return null;
return wrapper.data;
}
public void setData(T data) throws IllegalAccessError
{
if (wrapper != null)
throw new IllegalAccessError();
else
wrapper = this.new Wrapper<>(data);
}
#Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Worm<T> other = (Worm<T>) obj;
return Objects.equals(this.getData(), other.getData());
}
#Override
public int hashCode() {
return Objects.hashCode(this.getData());
}
final private class Wrapper<T> {
final private T data;
Wrapper(T data) {
this.data = data;
}
}
}
private final long mId;
final reference cann't be modified at runtime as per java spec. So, once you declared it as final, mId can't point to something else throughout its lifetime (Unless you use reflection (or) wrap the value in object and modify it through other reference).
You can set later a global final Variable only in your constructor. Example:
public class ClassA {
private final long mID;
public ClassA(final long mID) {
this.mID = mID;
}
}
In this case in each constructor you have to initialize the final variable.
you have to initialize the constructor as soon as you create it, or you could initialize it at the max, in the constructor. Not later than that..
NO it can not be done
if you can declare final at one place and initialize it later, Then What is the mean of final.
If you want to have a constant ID, why don't you use Shared Preferences , store it in SP and retrieve whenever want.
I often have a situation in my Java code when I need to set a boolean flag inside an inner class. It is not possible to use primitive boolean type for that, because inner class could only work with final variables from outside, so I use pattern like this:
// class from gnu.trove is not of big importance, just to have an example
private final TIntIntHashMap team = new TIntIntHashMap();
// ....... code ............
final boolean[] flag = new boolean[]{false};
team.forEachValue(new TIntProcedure() {
#Override
public boolean execute(int score) {
if(score >= VICTORY_SCORE) {
flag[0] = true;
}
return true; // to continue iteration over hash map values
}
});
// ....... code ..............
The pattern of final array instead of non-final variable works well, except it is not look beautiful enough to me. Does someone know better pattern in Java ?
Use AtomicBoolean.
Here's a popular StackOverflow question about this issue: Why are only final variables accessible in anonymous class?
How about having a generic holder class which holds object of any type. In your case, it can hold a Boolean type. Something like:
class Holder<T> {
private T genericObj;
public Holder(T genericObj) {
this.genericObj = genericObj;
}
public T getGenericObj() {
return genericObj;
}
public void setGenericObj(T genericObj) {
this.genericObj = genericObj;
}
}
And use it as:
public class Test {
public static void main(String[] args) throws Exception {
final Holder<Boolean> boolHolder = new Holder<Boolean>(Boolean.TRUE);
new Runnable() {
#Override
public void run() {
boolHolder.setGenericObj(Boolean.FALSE);
}
};
}
}
Of course, this has the usual problems that occur with mutable objects that are shared across threads but you get the idea. Plus for applications where memory requirements are tight, this might get crossed off when doing optimizations in case you have a lot of invocations of such methods. Also, using AtomicReference to swap/set references should take care of use from multiple threads though using it across threads would still be a bit questionable.
There are situations where this is the best pattern.
The only improvement I can suggest is return false when you have found a match.
One problem is that the TIntIntHashMap does not have a fold/reduce method so you have to simulate it using foreach. You could try to write your own class extending TIntIntHashMap adding a reduce method.
Other solution is to just extend TIntProcedure to have a value. Something like:
abstract class TIntProcedureWithValue<T> implements TIntProcedure {
private T accumulator;
public T getValue() {return accumulator;}
}
Then you can pass an instance of this class to foreach, set the internal accumulator instead of the external flag array, and get the resulting value afterwards.
I am not familiar with gnu.trove, but generally it's better for the "algortihm" function to be more specific, leaving less code here.
private final IntIntHashMap team = new IntIntHashMap();
boolean found = team.value().containsMatch(new IntPredicate() {
public boolean is(int score) {
return score >= VICTORY_SCORE;
}
});
(More concise syntax should be available in Java SE 8.)
maybe something like that? (implements or extends... I don't know what is TIntProcedure, unfortunately) :
class FlagResult implements TIntProcedure {
boolean flag = false;
#Override
public boolean execute(int score) {
flag = score >= VICTORY_SCORE;
return !flag;
}
};
FlagResult result = new FlagResult();
team.forEachValue(result);
boolean flag = result.flag;
Eg.
boolean isCurrent = false;
What do you name its getter and setter?
Suppose you have
boolean active;
Accessors method would be
public boolean isActive(){return this.active;}
public void setActive(boolean active){this.active = active;}
See Also
Java Programming/Java Beans
Code Conventions for the Java Programming Language
http://geosoft.no/development/javastyle.html#Specific
is prefix should be used for boolean variables and methods.
isSet, isVisible, isFinished, isFound, isOpen
This is the naming convention for
boolean methods and variables used by
Sun for the Java core packages. Using the is prefix solves a common
problem of choosing bad boolean names
like status or flag. isStatus or
isFlag simply doesn't fit, and the
programmer is forced to chose more
meaningful names.
Setter methods for boolean variables
must have set prefix as in:
void setFound(boolean isFound);
There are a few alternatives to the is
prefix that fits better in some
situations. These are has, can and
should prefixes:
boolean hasLicense();
boolean canEvaluate();
boolean shouldAbort = false;
For a field named isCurrent, the correct getter / setter naming is setCurrent() / isCurrent() (at least that's what Eclipse thinks), which is highly confusing and can be traced back to the main problem:
Your field should not be called isCurrent in the first place. Is is a verb and verbs are inappropriate to represent an Object's state. Use an adjective instead, and suddenly your getter / setter names will make more sense:
private boolean current;
public boolean isCurrent(){
return current;
}
public void setCurrent(final boolean current){
this.current = current;
}
I believe it would be:
void setCurrent(boolean current)
boolean isCurrent()
Maybe it is time to start revising this answer? Personally I would vote for setActive() and unsetActive() (alternatives can be setUnActive(), notActive(), disable(), etc. depending on context) since "setActive" implies you activate it at all times, which you don't. It's kind of counter intuitive to say "setActive" but actually remove the active state.
Another problem is, you can can not listen to specifically a SetActive event in a CQRS way, you would need to listen to a 'setActiveEvent' and determine inside that listener wether is was actually set active or not. Or of course determine which event to call when calling setActive() but that then goes against the Separation of Concerns principle.
A good read on this is the FlagArgument article by Martin Fowler: http://martinfowler.com/bliki/FlagArgument.html
However, I come from a PHP background and see this trend being adopted more and more. Not sure how much this lives with Java development.
There is a markable point between setter/getter method of the data type Boolean and boolean in side a class ( for pojo/entity).
For both Boolean and boolean the setter method should be setXXX() but getter method would be getXXX() and isXXX() respectively
Example:
(a) if property is defines as Boolean
private Boolean active;
the setter/getter method
public Boolean getCheck() { // getXXX()
return check;
}
public void setCheck(Boolean check) {
this.check = check;
}
(b) if property is defines as boolean
private boolean check;
the setter/getter method
public boolean isCheck() { // isXXX()
return check;
}
public void setCheck(boolean check) {
this.check = check;
}
It should just be get{varname} like every other getter. Changing it to "is" doesn't stop bad variable names, it just makes another unnecessary rule.
Consider program generated code, or reflection derivations.
It's a non-useful convention that should be dropped at the first available opportunity.
It is highly recommended to use an adjective to name a boolean field. If you generate getter and setter using IntelliJ, you will find out that the getter is isCurrent() for both of boolean fields current and isCurrent.
We can take a look at IntelliJ community source code, its test data shows that no matter whether your boolean field name starts with is or not, the name of getter starts with is.
class Getter {
boolean foo;
boolean isBar;
boolean hasBaz;
#java.lang.SuppressWarnings("all")
public boolean isFoo() {
return this.foo;
}
#java.lang.SuppressWarnings("all")
public boolean isBar() {
return this.isBar;
}
#java.lang.SuppressWarnings("all")
public boolean isHasBaz() {
return this.hasBaz;
}
}
It will be very confusing when you want to call the getter, when you boolean field name starts with is. Besides, when your colleagues want to get the value of a boolean field you defined, they will only know the getter' s name instead of the field' s name. In that case, the prefix is is not necessary.
Here is another example, when I retrieve data from database to instantiate a object of Employee, the value of isRetired is always false. Because Java does not find an appropriate setter, the value of a boolean field is always default value, say false, which is not expected.
class Employee{
private int age;
private boolean isRetired;
...
public boolean setRetired(boolean isRetired){
this.isRetired = isRetired;
}
}
private boolean current;
public void setCurrent(boolean current){
this.current=current;
}
public boolean hasCurrent(){
return this.current;
}
Setter: public void setCurrent(boolean val)
Getter: public boolean getCurrent()
For booleans you can also use
public boolean isCurrent()
As a setter, how about:
// setter
public void beCurrent(boolean X) {
this.isCurrent = X;
}
or
// setter
public void makeCurrent(boolean X) {
this.isCurrent = X;
}
I'm not sure if these naming make sense to native English speakers.