As part of my application, the database stores "badges" in a user's record in the database. I use the bitwise operator as (as far as I know) no two additions of them can have the same solution. Here are the values:
enum Badge {
SUPPORTER(1),
ALPHA(1 << 1),
BETA_OWNER(1 << 2),
BOOSTER(1 << 3),
ONE_MONTH(1 << 4),
THREE_MONTH(1 << 5),
SIX_MONTH(1 << 6),
ONE_YEAR(1 << 7),
TWO_YEAR(1 << 8),
;
public int value;
public int resolve() {
return value;
}
Badge(int i) {
value = i;
}
}
The method of storing them is as simple as adding up the values of each badge corresponding to the user. However, decoding this value is more tricky.
How would I go about decoding the value from the database into a list of badges that I can manipulate?
CodePudding user response:
Use an EnumSet
.The EnumSet can hold each item only once (it's a set). Have a look here for storing values in a database. There are solutions for decoding manually, or you can use Apache Commons for that.
CodePudding user response:
Lets try something like this:
public enum BADGES {SUPPORTER, ALPHA, BETA_OWNER, BOOSTER, ONE_MONTH, THREE_MONTH, SIX_MONTH, ONE_YEAR, TWO_YEAR};
public HashMap<BADGES, Integer> badgesToIntegerMap = /* initialize map where integers are mapped to badges */
public HashMap<Integer, BADGES> integerToBadgesMap = /* initialize map where badges are mapped to their integers */
public List<BADGES> getUserBadges(int userStatus) {
List<BADGES> retVal = new ArrayList<BADGES>();
// Start from highest one, being TWO_YEAR at time of writing
int currentBadge = 1 << 8; //
while (currentBadge > 0) { // These two should be replaced by iterating the badgesToIntegerMap's values
if (userStatus && currentBadge == 1) {
retVal.add(integerToBadgesMap.get(currentBadge));
}
currentBadge = currentBadge >> 1;
}
return retVal;
}
Or you know, just pass these integers into a constructor of each individual badge, and you can avoid one lookup.