Saturday, 24 August 2013

How can I update Java hashmap values by previous value

How can I update Java hashmap values by previous value

This question is a bit more complex that the title states.
What I am trying to do is store a map of {Object:Item} for a game where
the Object represents a cupboard and the Item represents the content of
the cupboard (i.e the item inside).
Essentially what I need to do is update the values of the items in a
clockwise (positive) rotation; though I do NOT want to modify the list in
any way after it is created, only shift the positions of the values + 1.
I am currently doing almost all That I need, however, there are more
Object's than Item's so I use null types to represent empty cupboards.
However, when I run my code, the map is being modified (likely as it's in
the for loop) and in turn, elements are being overwritten incorrectly
which after A while may leave me with a list full of nulls (and empty
cupboards)
What I have so far...
private static Map<Integer, Integer> cupboardItems = new HashMap<Integer,
Integer>();
private static Map<Integer, Integer> rewardPrices = new HashMap<Integer,
Integer>();
private static final int[] objects = { 10783, 10785, 10787, 10789, 10791,
10793, 10795, 10797 };
private static final int[] rewards = { 6893, 6894, 6895, 6896, 6897 };
static {
int reward = rewards[0];
for (int i = 0; i < objects.length; i++) {
if (reward > rewards[rewards.length - 1])
cupboardItems.put(objects[i], null);
else
cupboardItems.put(objects[i], reward);
reward++;
}
}
// updates the items in the cupboards in clockwise rotation.
for (int i = 0; i < cupboardItems.size(); i++) {
if (objects[i] == objects[objects.length - 2])
cupboardItems.put(objects[i],
cupboardItems.get(objects[0]));
else if (objects[i] == objects[objects.length - 1])
cupboardItems.put(objects[i],
cupboardItems.get(objects[1]));
else
cupboardItems.put(objects[i],
cupboardItems.get(objects[i + 2]));
}
So how may I modify my code to update so i get the following results..
======
k1:v1
k2:v2
k3:v3
k4:none
=======
k1:none
k2:v1
k3:v2
k4:v3
?

No comments:

Post a Comment