Store array of settings into database row


Store array of settings into database row
I want to optimize into database row application settings. Something like this
10 - enabled option 1;
12 - enabled option 2;
13 - enabled option 3;
And the entire number is stored into database as 1073741823.
I tried to implement this:
public void test()
// Let's say you get a String representing your option from your database
String optionFromDB= "132456";
// optionFromDB is a number like "132456"
// We transform it to bigDecimal:
BigDecimal myOptions=new BigDecimal(optionFromDB);
// Then we can use it.
// enable the option X (X is a number)
myOptions.setBit(2);
// Disable option X
myOptions.clearBit(2);
// Save the options to the db:
String newValToSave=myOptions.toString();
// do something if option x enable:
if (myOptions.testBit(123))
System.out.println("test");
How I can implement this properly?
2 Answers
2
Assume value is an integer - this will give you 32 options. If that's not enough, you can take long (64 bits) or apply the same logic to any number of bits.
This is Java example.
– jurez
2 days ago
Can you show me with Java methods and etc.
– Peter Penzov
2 days ago
public int enableBit(int value, int bit) return value
. I'm sure you can figure out the rest.– jurez
2 days ago
public int enableBit(int value, int bit) return value
I'm not sure how to ge the final result -> 1073741823
– Peter Penzov
2 days ago
Well, just use a number, let's call it state. The type should be decided according to the number of options that you will have. For instance if you have 10 options, Integer
is more than enough. For each option you can use one bit of this integer state.
Integer
So to set the first option just set first bit, and in general the ith bit for the ith option. To see if the ith option is enabled check if the ith bit of the state is set.
For setting the ith bit you can use the following code:
state |= 1 << i;
For testing the ith bit the following:
state & (1L << i)) != 0;
For clearing the ith bit use:
state &= ~(1 << i);
Can you show me some code example how to implement it?
– Peter Penzov
2 days ago
Yes, in a second.
– NiVeR
2 days ago
Can you please show me complete Java code with methods and etc.
– Peter Penzov
2 days ago
It is, just use it according to needs.
– NiVeR
2 days ago
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Thanks, can you show me some Java example, please?
– Peter Penzov
2 days ago