I am writing a code for displaying time vs size.
I am using a hashmap to make entries.The problem is that it do the calculations correctly but in the end when i try to print out the hashmap ,it does not display all the results for 7 minutes.Instead it displays the result of last entry 7 times.I have tried a lot to figure out the problem but couldn’t.Plzz help me out
Here is my code
public class Analysis
{
public static class KeepTime
{
String time;
long TotalSize;
}
Main f1 = new Main();
public static int j = 0;
public static int check = 0;
public HashMap<String, KeepTime> hMap_time = new HashMap<String, KeepTime>();
public KeepTime TimerInstance = new KeepTime();
void TimeBasedReporting()
{
String skey;
String key;
int k;
int y;
for (k = 1; k <= f1.Flows().size(); k++)
{
check = 0;
j = 0;
skey = Integer.toString(k);
if (hMap_time.isEmpty())
{
//some code
key = Integer.toString(hMap_time.size() + 1);
hMap_time.put(key, TimerInstance);
j = 1;
}
else if (check == 0 && j == 0)
{
for (y = 1; y <= hMap_time.size(); y++)
{
//some code
}
}
}
if (check == 0 && j == 0)
{
// some code
key = Integer.toString(hMap_time.size() + 1);
hMap_time.put(key, TimerInstance);
}
else
{}
}
}
}
Following is the output
03:08:39,AM 424
03:08:39,AM 424
03:08:39,AM 424
03:08:39,AM 424
03:08:39,AM 424
03:08:39,AM 424
03:08:39,AM 424
03:08:39,AM 424
03:08:39,AM 424
03:08:39,AM 424
You’re creating a single instance of
KeepTimeand using a reference to that object as the value in various key/value pairs.You should be creating a new instance each time you add a new entry, if you want them to be independent. (And yes, I agree with the comment that you almost certainly don’t want a map here – but you’d get the same problem if you added the same reference to a list multiple times, too.)